Table A:
id | status |
---|---|
1 | 1 |
2 | 4 |
Table B:
id | status | a_id |
---|---|---|
1 | 1 | 1 |
2 | 3 | 1 |
3 | 5 | 2 |
Table A (
id int,
status int);
Table B(
id int,
status int,
a_id int foreignt key reference A
);
How to make query that return such output, when I seek status in (1,3)?
id | status | arrayjson |
---|---|---|
1 | 1 | [{id=1,status=1,a_id=1},{id=2,status=3,a_id=1}] |
If I seek status in ( 3 ), it should return:
id | status | arrayjson |
---|---|---|
1 | 1 | [{id=2,status=3,a_id=1}] |
If I seek status in ( 4 ), it should return:
id | status | arrayjson |
---|---|---|
2 | 4 | [] |
If I seek status in ( 5 ) it should return:
id | status | arrayjson |
---|---|---|
2 | 4 | [{id=2,status=4,a_id=2}] |
3
Answers
finally find the best solution
Given your set of seek status values, you can use:
GENERATE_SERIES
, to generate your possible seek_status valuesJSON_BUILD_OBJECT
, to build your json beginning from your B tableJSON_AGG
, to aggregate your jsonWHERE v.seek_status IN (1,3)
, to change the seek_status you needORDER BY A.status DESC LIMIT 1
, to get the highest status possible among all output recordsCheck the demo here.
This is you basic query with the filter on status from table
B
(example for status 1,3)Now you need only to group on the first two columns and aggregate the JSON array.
json_agg and json_build_object are the solution