【问题标题】:SQL double aggregate function with condition带条件的 SQL 双聚合函数
【发布时间】:2014-09-28 18:52:47
【问题描述】:

我有一张桌子,看起来像是在闲置。

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 作为数据库。 我如何查询表以获取输出为上? 谢谢。

【问题讨论】:

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


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      很简单,您是要优化还是要我们为您编写查询?

      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
      

      【讨论】:

      • "或者您希望我们为您编写查询?"哈!我很确定这是“为 meh 编写代码!”题。好的第一个(或第三个)答案...欢迎来到 SO 并继续保持下去
      • 对不起伙计,起初我为我的问题选择了错误的标题,我认为这个查询对我来说已经足够优化了。谢谢你的回答。
      猜你喜欢
      • 2017-11-25
      • 2018-04-21
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 2011-05-26
      相关资源
      最近更新 更多