【问题标题】:Merging two (or more) "group by" like query result table合并两个(或更多)“分组依据”,如查询结果表
【发布时间】:2020-08-12 02:49:10
【问题描述】:

我有一张这样的桌子:

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  

任何想法可以做什么?

【问题讨论】:

    标签: sql postgresql aggregation


    【解决方案1】:

    使用条件聚合:

    select name, 
           sum(area) filter (where condition1) as sum1, 
           sum(area) filter (where condition2) as sum2
    group by name;
    

    【讨论】:

    • 感谢您提供真正快速的解决方案!
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    相关资源
    最近更新 更多