Order by value of an arbitrary attribute in hstore
I have entries like these:
id, hstore_col
1, {a: 1, b: 2}
2, {c: 3, d: 4}
3, {e: 1, f: 5}
How do I order them by max / min value inside hstore for any attribute ?
The result should be like this (order below):
id, hstore_col
1, {a: 1, b: 2}
3, {e: 1, f: 5}
2, {c: 3, d: 4}
I know I can only order them by a specific attribute like this: my_table.hstore_fields -> 'a'
but it doesn't work for my problem.
+3
source to share
3 answers
If you know all the elements, you can simply put them all together like this:
ORDER BY greatest(my_table.hstore_fields -> 'a', my_table.hstore_fields -> 'b',my_table.hstore_fields -> 'c', my_table.hstore_fields -> 'd', my_table.hstore_fields -> 'e', my_table.hstore_fields -> 'f')
or
ORDER BY least(my_table.hstore_fields -> 'a', my_table.hstore_fields -> 'b',my_table.hstore_fields -> 'c', my_table.hstore_fields -> 'd', my_table.hstore_fields -> 'e', my_table.hstore_fields -> 'f')
+2
source to share
Using svals
, you can create an exploded version of the values hstore_col
- then you can sort by those values ββand get the first record from each of them. Undoubtedly a much more efficient way to do it, but here's the first pass:
select my_table.id, my_table.hstore_col
from my_table
join (
select id, svals(hstore_col) as hstore_val
from my_table
) exploded_table
on my_table.id = exploded_table.id
group by my_table.id, my_table.hstore_col
order by my_table.id, exploded_table.hstore_val desc
0
source to share