具有条件的SQL双重聚合函数

时间:2014-08-05 23:56:45

标签: sql postgresql group-by aggregate-functions window-functions

我有一张看起来像是休息的桌子。

DepartmentId    | Salary  | Status       
----------------------------------
1               |  5     | active
1               |  10     | active
1               |  15     | passive
1               |  20     | passive

我想选择这个表来减少输出。

Columns:
DepartmentId,
Sum of salary where status is active ,
Sum of salary where status is passive.


DepartmentId    | Sum(salary) where status is active  | Sum(salary) where status is passive       

-------------------------------------------------------------------------------------------
    1           |  15                                 | 35

我使用postgresql作为数据库。 如何查询表以获得输出为上限? 感谢。

2 个答案:

答案 0 :(得分:3)

select
    departmentid,
    sum(case status when 'active' then salary else 0 end) as active_salary_sum,
    sum(case status when 'passive' then salary else 0 end) as passive_salary_sum
from t
group by departmentid

答案 1 :(得分:3)

它非常简单,您想要在此进行优化还是希望我们为您编写查询?

Select DepartmentId,
Sum (case when status='active' then salary end) as SumOfActive ,
Sum (case when status='passive' then salary end) as SumOfPassive
From TableName
Group By DepartmentId