需要从案例陈述中添加金额总和

时间:2017-08-24 17:52:14

标签: sql sql-server

需要根据以下条件获取emp表的金额总和:

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)以外的类型与年份相对应

条件2:如果在特定年份季度中只有类型(3,4)和状态=' A'我们可以添加它们

来自上述条件

在2015年,我们只有1条记录,类型1   我们需要选择3000

在2015年,我们只有1条记录类型:1   我们需要挑选7000(我们需要忽略所有其他类型的记录)

2015年有两种类型的记录(6,7)     我们需要选择19000

在2015年4月只有类型:3记录我们需要选择2000

so the total output needed is:31000

应显示31000

2 个答案:

答案 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

答案 1 :(得分: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;
相关问题