I have this table:
id | period_type | period | commission |
---|---|---|---|
123456 | Daily | 10 | 10 |
123456 | Monthly | 3 | 11 |
123456 | Daily | 5 | 12 |
123456 | Monthly | 1 | 13 |
123457 | Monthly | 6 | 14 |
123457 | Daily | 5 | 15 |
123457 | Monthly | 9 | 16 |
(Period type is int 1&2, but for example I wrote it by text)
I need get records with id and single jsonb with period_type, period and commission column. This jsonb must have max period with max period type. For example, id – 123456, period_type – ‘Monthly’, period – 3, commission – 11.
I know how get array of periods (jsonb_build_object
and jsonb_agg
), but don’t know how get 1 period with such conditions.
2
Answers
Next query can be written easier, but I am always seem to have problem when multiple MAX values pop-up in 1 query (like getting the commission for the max period for the max period_type):
it retruns:
This query can be used as a sub-query to get JSON:
output:
see: DBFIDDLE
This is a standard Top-1-Per-Group problem. Use
ROW_NUMBER
to get the top value in each group, thenjsonb_agg
to aggregate it up into a JSON array.db<>fiddle