2013-10-15 39 views
0

我已經查看了透視圖相關的查詢,但似乎找不到與我想要做的匹配的查詢。我有一個表,如下所示: -t-sql在聚合列上轉軸

type | iscurrent 
----------------- 
A  | 1 
A  | 1 
A  | 0 
B  | 1 
B  | 1 
B  | 1 
C.... 

我想這樣看起來如下轉動這個數據,iscurrent場僅會0和1的在裏面。

TYPE | 1 | 0 
----------------- 
A  | 2 | 1 
B  | 3 | 0 
C  | ... 

我到目前爲止的代碼是

SELECT loadid, '1', '0' 
FROM (
SELECT iscurrent, loadid 
FROM #table) up 
PIVOT (sum(iscurrent) FOR iscurrent IN ([1], [0])) AS pvt 
ORDER BY loadid 
GO 

我有點操作錯誤,當我嘗試運行的代碼?

回答

1

嘗試

SELECT loadid, [1], [0] 

PIVOT (count(isCurrent) FOR iscurrent IN ([1], [0])) AS pvt 

即:

SELECT loadid, [1],[0] 
FROM ( SELECT iscurrent, loadid FROM #table) up 
PIVOT (count(iscurrent) FOR iscurrent IN ([1], [0])) AS pvt 
ORDER BY loadid 
+0

謝謝@podiluska工作完美 – Spufferoo