根据多列中存在的ID汇总发票金额

时间:2017-04-10 17:15:34

标签: sql-server

假设我有一个表格,其中包含按行和6列的发票行,其中员工ID可以标记为该发票。员工ID不能连续复制,但不同发票行的不同列中可以存在相同的员工ID。在下表中,REP 1的总金额应为500。

enter image description here

我希望能够按员工ID(REP 1,REP 2等)总计总金额。我可以使用大型联合查询来执行此操作,但问题是我有一个大约450个员工ID的列表,我需要总结。有没有办法让一个查询吐出一份员工ID及其总金额列表?

2 个答案:

答案 0 :(得分:2)

我建议使用cross apply

select v.e, sum(t.amount)
from t cross apply
     (values (slot1), (slot2), (slot3), (slot4), (slot5), (slot6)) v(e)
group by v.e;

注意:这假定您使用的是SQL Server。

答案 1 :(得分:1)

加入表是一种方式......

select e.employee_id,
       sum(i.amount)
  from invoice i,
  join employee e on (e.employee_id in (i.slot1, i.slot2, i.slot3, i.slot4, i.slot5, i.slot6))
 group by e.employee_id;

另一种方式......

select employee_id,
       sum(amount)
from (
    select slot1 employee_id, sum(amount) amount from invoice group by slot1 union
    select slot2, sum(amount) from invoice group by slot2 union all
    select slot3, sum(amount) from invoice group by slot3 union all
    select slot4, sum(amount) from invoice group by slot4 union all
    select slot5, sum(amount) from invoice group by slot5 union all
    select slot6, sum(amount) from invoice group by slot6
) as q1
group by employee_id;