首页 文章

分别对正负值求和

提问于
浏览
0

我有一张桌子:

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

而且我想写一个查询来汇总数据,在一列中应该只有正数量的od钱在另一列只有负数 . 输出应如下所示:

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

请帮我改写我的查询以纠正输出 .

2 回答

  • 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;
    
  • 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,这是不同的,因此它的副本

相关问题