比较总和()来总结

比较总和()来总结

问题描述:

的其他行,所以我有这个表比较总和()来总结

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 

我想获得这并不所有类型有与其他类型相同的总和() 所以在SQL我会有这样的事情

my expected output is 

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

因为类型A = 100,那里有B型谁也= 100

+0

总是包含您的Oracle版本。例如,在我的解决方案中,我使用子构造的查询,只要它们有意义 - 但它们仅在Oracle 11.1之后才可用。如果您的版本为10或以下,则必须使用“旧”子查询语法重新编写查询。 – mathguy

一种方法是使用窗口函数:

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; 
+0

有没有更简单的方法做到这一点,而不使用分区? –

+0

'partition by' *是更简单的方法。 –

使用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.