合并两个(或更多)"group by" 喜欢的查询结果 table
Merging two (or more) "group by" like query result table
我有一个 table 这样的:
name area timestamp
aa 10 timestamp
aa 12 timestamp
aa 22 timestamp
bb 11 timestamp
bb 11 timestamp
cc 11 timestamp
我可以做到以下几点:
select name, sum(area) as sum1 from mytable where "condition1 based on timestamp" group by name;
select name, sum(area) as sum2 from mytable where "condition2 based on timestamp" group by name;
但我真正需要的应该是这样的:
name sum1 sum2
aa 444 555
bb 666 777
cc 111 222
有什么想法吗?
使用条件聚合:
select name,
sum(area) filter (where condition1) as sum1,
sum(area) filter (where condition2) as sum2
group by name;
我有一个 table 这样的:
name area timestamp
aa 10 timestamp
aa 12 timestamp
aa 22 timestamp
bb 11 timestamp
bb 11 timestamp
cc 11 timestamp
我可以做到以下几点:
select name, sum(area) as sum1 from mytable where "condition1 based on timestamp" group by name;
select name, sum(area) as sum2 from mytable where "condition2 based on timestamp" group by name;
但我真正需要的应该是这样的:
name sum1 sum2
aa 444 555
bb 666 777
cc 111 222
有什么想法吗?
使用条件聚合:
select name,
sum(area) filter (where condition1) as sum1,
sum(area) filter (where condition2) as sum2
group by name;