title,date,pcs
1,25,10
2,26,20
3,27,30
上列是db中的結果.
如何用 sql 中的case或是其它語法改出如下的結果嗎?
title,25,26,27,sum
1,10,0,0,0,10
2,0,20,0,0,20
3,0,0,30,30
感謝幫忙.
<pre class="c" name="code">
select title,
sum(case when date='25' then pcs else 0 end) as 25,
sum(case when date='26' then pcs else 0 end) as 26,
sum(case when date='27' then pcs else 0 end) as 27,
sum(pcs) as sum_pcs
from tablename
group by title
SELECT * FROM
(
SELECT *,sum(PCS)As Sum1
FROM testTable group By title,date,pcs
) AS X
PIVOT(
sum(PCS)
FOR date in
([25],[26],[27])
) AS PVT
group by [title],[25],[26],[27],[sum1]