2017-08-24 55 views
-1

添加量的总和需要得到量的总和基于以下条件的表emp:需要从一个case语句

empid yearquarter  type status amount orderdate 
101  20151   1 A  3000  01-18-2015 
101  20152   3 A  4000  05-09-2015 
101  20152   4 A  5000  06-09-2015 
101  20152   4 P  5000  06-09-2015 
101  20152   1 A  7000  06-09-2015 
101  20153   6 A  9000  09-11-2015 
101  20153   7 A  10000 09-11-2015 
101  20154   3 A  2000  12-12-2015 

条件1:只需添加状态=“A”和比(3,4)与各自的yearquarter其他类型

条件2:如果在某一去年同期只有类型(3,4)和状态=“A”,我们可以将它们添加

FROM上述条件

在20151,我们只有1只记录1型 就需要从3000

在20152,我们只有1个纪录类型:1 就需要从7000(我们需要忽略不同类型的所有其他记录)

在20153有类型的(6,7) 就需要从19000

IN 20154两条记录,只有TYPE:3记录就需要从2000

so the total output needed is:31000 

31000应显示

+1

你有什么试过的?这不是一个代码写入服务。 – nicomp

+1

停止滚动回大喊 – Lamak

+0

我要为两种不同情况的案例陈述,但总结总计我不能 –

回答

0

试试这个应该足够你的要求

select case when status ='A' AND type in (3,4) then SUM(amount) as amount 
      when status ='A' AND type not in (3,4) then yearquarter,amount end 
0

这是由条件的多层复杂。如果我理解正确:

select yearquarter, 
     (case when sum(case when type not in (3, 4) then 1 else 0 end) = 0 
      then sum(amount) 
      else sum(case when type not in (3, 4) then amount else 0 end) 
     end) 
from t 
where status = 'A' 
group by yearquarter; 
+0

我已经修改了这个问题......您共享的查询正在挑选错误的值 –

+0

如何将年度总额添加到单个值中 –