如何在左边合计两列,在第三列中显示总数

时间:2012-08-15 20:30:40

标签: sql-server-2008

我有一张类似于下面的表

Date     | institution | qty1 | qty2
1 Aug 12 | xyz         |  0   | 5
1 Aug 12 | xyz         |  0   | 17
1 Aug 12 | abc         | 12   | 0
2 Aug 12 | abc         | 33   | 0
2 Aug 12 | xyz         | 0    | 57 

我想要类似于下面的输出

Date     | ABC     | XYZ  | Total
1 Aug 12 | 12      |  22  | 34
2 Aug 12 | 33      |  57  | 90
Total    | 45      | 79   | 124

现在我编写了一个只显示前三列的查询。我不知道如何添加最后一个总列

select date, sum (case when institution = 'abc', qty1 else 0 end) as ABC,
sum(case when institution =  'xyz', qty2 else 0 end) as XYZ
group by date
with rollup

1 个答案:

答案 0 :(得分:1)

你非常接近 - 我认为应该这样做:

select
  date
, sum (case when institution = 'abc' then qty1 else 0 end) as ABC
, sum(case when institution =  'xyz' then qty2 else 0 end) as XYZ
, sum(qty1+qty2) as Total
from mytable
group by date
with rollup

这是link to this example on sqlfiddle