【问题标题】:sum positive and negative values separately分别对正负值求和
【发布时间】:2018-12-10 09:57:44
【问题描述】:

我有一张桌子:

NAME    MONEY
Jane    100  
Chris  -100  
Jane     50  
Ann     -10  
Jane    -25  
Ann      17

我想编写一个查询来汇总数据,在一列中应该只有正数,而在另一列中只有负数。输出应如下所示:

NAME    SUM_POSITIVE    SUM_NEGATIVE
Jane    150             -25
Chris   0               -100
Ann     17              -10

查询:

select name, sum(money) from TABLE where money>0 group by name
union 
select name, sum(money) from TABLE where money<0 group by name;

几乎显示了我想要的,但结果有重复的名称和两列而不是三列:

NAME    SUM
Ann     -10
Ann      17
Jane    -25
Jane    150
Chris  -100

请帮我重写我的查询以正确输出。

【问题讨论】:

    标签: sql


    【解决方案1】:

    用例当

     select name, sum(case when money>0 then money end) SUM_POSITIVE
    ,sum(case when money<0 then money end) SUM_NEGATIVE
    from TABLE  group by name
    

    你得到重复的名字,因为联合运算符只合并所有列值都相同的行,因为 Ann 包含 -10 和 17,它们是不同的,所以它是重复的

    【讨论】:

      【解决方案2】:

      您可以改为条件聚合:

      select name, 
             sum(case when money > 0 then money end) as SUM_POSITIVE,
             sum(case when money < 0 then money end) as SUM_NEGATIVE 
      from TABLE
      group by name;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-21
        • 2016-02-20
        • 1970-01-01
        • 1970-01-01
        • 2019-02-26
        • 1970-01-01
        • 1970-01-01
        • 2017-11-29
        相关资源
        最近更新 更多