同一列中的总计差异

时间:2013-08-22 20:24:41

标签: sql sql-server-2008

我有这个专栏,

  ID  Year  ColumnDesc  Amount   
  1    2000   Taken       100
  1    2000  NotTaken    10
  1    2001   Taken       200
  1    2001  NotTaken   100

所以我需要在具有相同ID和年份的金额之间做差异所以我的表应该是这样的。

  ID  Year  ColumnDesc  Amount   
  1    2000   Taken    90
  1    2001   Taken    100

任何人都可以帮助我..

1 个答案:

答案 0 :(得分:5)

我认为你想要条件聚合:

select id, year, 'Taken' as ColumnDesc,
       sum(case when ColumnDesc = 'Taken' then Amount
                when ColumnDesc = 'Not Taken' then - Amount
                else 0
           end) as Amount
from t
group by id, year;