将sum()与其他sum行进行比较

时间:2016-09-21 02:45:44

标签: sql oracle sum aggregate-functions

所以我有这张桌子

type   total
------------
A    |  50
A    |  50
B    |  100
C    |  50
C    |  200
D    |  150
D    |  300

此代码仅供参考

select type,Sum(total)
From table A
group by type

我希望得到与其他类型没有相同Sum()的所有类型 所以在SQL中我会有这样的东西

my expected output is 

type    total
-------------
C    |  250
D    |  450

因为类型A = 100而类型B也是= 100

2 个答案:

答案 0 :(得分:1)

一种方法使用窗口函数:

select type, total
from (select type, sum(total) as total,
             count(*) over (partition by sum(total)) as cnt
      from table A
      group by type
     ) a
where cnt = 1;

答案 1 :(得分:0)

使用GROUP BY两次 - 首先按类型分组以计算总计,然后按总计除去那些使用"等于"总计:

with
     inputs ( type, total ) as (
       select 'A',  50 from dual union all
       select 'A',  50 from dual union all
       select 'B', 100 from dual union all
       select 'C',  50 from dual union all
       select 'C', 200 from dual union all
       select 'D', 150 from dual union all
       select 'D', 300 from dual
     ),
     grouped ( type, grand_total ) as (
       select type, sum(total)
       from   inputs
       group by type
     )
select max(type) as type, grand_total
from   grouped
group by grand_total
having count(type) = 1
;


TYPE GRAND_TOTAL
---- -----------
D            450
C            250

2 rows selected.