合并两个(或多个)"分组 "一样的查询结果表。

问题描述 投票:0回答:1

我有一张这样的表格。

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  

有什么办法吗?

postgresql pandas-groupby
1个回答
1
投票

使用条件聚合。

select name, 
       sum(area) filter (where condition1) as sum1, 
       sum(area) filter (where condition2) as sum2
group by name;
© www.soinside.com 2019 - 2024. All rights reserved.