2012-08-15 20 views
1

总结两列我有类似下面如何在左,显示总在第三列

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

你很接近 - 我想这应该这样做:

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

+0

你需要包括在其他两列使用的条件... – 2012-08-15 20:45:34

+0

谢谢dasblinkenlight ...... – user1449596 2012-08-15 20:48:33

+0

@DanJ不,条件是不需要的,因为'else'分支总是零,因为除了'abc'和'xyz',没有别的选择。 – dasblinkenlight 2012-08-15 20:48:37