Demo at db<>fiddle:个
create table stores(id int,is_open boolean,popularity_count int,created_date date);
insert into stores values
(1,true,2,'yesterday'),
(2,true,7,now()-'1 month 2 weeks'::interval),
(3,true,8,'today allballs'),
(4,true,9,'epoch'),
(5,true,999,'-infinity'),
(6,false,0,'now'),
(7,false,0,'tomorrow'),
(8,false,0,'infinity'),
(9,true,99,'2023-10-30 13:13');
您可以使用常规聚合,在外部添加order by
clause inside and a filter
:
select array_agg(stores order by popularity_count)
filter(where popularity_count>5)
as "most popular"
,array_agg(stores order by created_date)
filter(where now()-'5 days'::interval <= created_date)
as "newly added"
from stores where is_open;
most popular |
newly added |
{"(2,t,7,2023-10-02)","(3,t,8,2023-11-16)","(4,t,9,1970-01-01)","(9,t,99,2023-10-30)","(5,t,999,-infinity)"} |
{"(1,t,2,2023-11-15)","(3,t,8,2023-11-16)"} |
请注意,正infinity
和负infinity
在PostgreSQL中是valid date
and timestamp
.
使用to_json()
,你甚至可以得到你所展示的json示例.下面我使用它的jsonb
版本to_jsonb()
只是为了用jsonb_pretty()
漂亮地打印:
select jsonb_pretty(to_jsonb(payload))
from (
select array_agg(stores order by popularity_count)
filter(where popularity_count>5)
as "most popular"
,array_agg(stores order by created_date)
filter(where now()-'5 days'::interval <= created_date)
as "newly added"
from stores where is_open
) AS payload;
jsonb_pretty |
{ "newly added": [ { "id": 1, "is_open": true, "created_date": "2023-11-15", "popularity_count": 2 }, { "id": 3, "is_open": true, "created_date": "2023-11-16", "popularity_count": 8 } ], "most popular": [ { "id": 2, "is_open": true, "created_date": "2023-10-02", "popularity_count": 7 }, { "id": 3, "is_open": true, "created_date": "2023-11-16", "popularity_count": 8 }, { "id": 4, "is_open": true, "created_date": "1970-01-01", "popularity_count": 9 }, { "id": 9, "is_open": true, "created_date": "2023-10-30", "popularity_count": 99 }, { "id": 5, "is_open": true, "created_date": "-infinity", "popularity_count": 999 } ] } |