I have a json_metrics' column of the json data type in a PostgreSQL 10.9 database's table. The data in the column is an array of objects, with each having a sessions, entrances, month and year attribute. There is at most one object per month/year combination. So it looks like this, for example:
[
{"sessions":52,"entrances":55,"month":3,"year":2020},
{"sessions":59,"entrances":59,"month":4,"year":2020},
{"sessions":76,"entrances":76,"month":5,"year":2020}
]
I would like to be able to sort rows on either "sessions" or "entrances" for a given "month" and "year" combination stored in this json_metrics column. eg. Sort rows by descending 3/2020 sessions. If there was a column for sessions-2020-03 I would, of course, just "order by sessions-2020-03 desc" to do that.
Is what I am trying to do possible with a json column? I am open to changing the structure of the json, or changing the data type to jsonb if that is of any value.
sessionskey directly. If you are on an earlier PG, then you will need to usejson_array_elements()in a lateral join to turn this array into rows and use thewhereclause to filter it and thenorder by. I would like to help with an example, but I need to run out for the day.