2009-07-21 132 views
1

這裏如何創建數據透視表是我的查詢沒有總結列

CREATE view pivmehis WITH ENCRYPTION 
as 
SELECT APPROVED, [Not Approved] as REJECT, NULL 
FROM 
(SELECT MgtApproval 
from LeaveRequest) l 
PIVOT 
(
Sum (SchedId) --I DON'T WANT TO SUM THIS COLUMN 
FOR MgtApproval IN 
([APPROVED], [REJECT], [NULL])) as pvt 

原始表的結果:

MgtApproval  SchedId 
Approved   1 
Reject    2 
Null    3 
Approved   4 
Reject    5 
Null    6 

這是結果,我想查看:

Approved Reject  Null 
1          2          3          
4          5          6          

回答

5
SELECT rn, APPROVED, [Not Approved] as REJECT, NULL 
FROM (
     SELECT MgtApproval, SchedID, ROW_NUMBER() OVER (PARTITION BY mgtapproval ORDER BY SchedID) AS rn 
     FROM LeaveRequest 
     ) l 
     PIVOT 
     (
     MIN(SchedId) 
     FOR  MgtApproval IN 
       ([APPROVED], [Not Approved], [NULL]) 
     ) as pvt 

A PIVOT仍然需要任何聚合函數,但是這個保證最多聚合一列。

下面是樣本數據的查詢返回你想要什麼:

WITH leaveRequest aS 
(
SELECT 'APPROVED' AS mgtapproval, 1 AS SchedID 
UNION ALL 
SELECT 'Reject' AS mgtapproval, 2 AS SchedID 
UNION ALL 
SELECT 'NULL' AS mgtapproval, 3 AS SchedID 
UNION ALL 
SELECT 'APPROVED' AS mgtapproval, 4 AS SchedID 
UNION ALL 
SELECT 'Reject' AS mgtapproval, 5 AS SchedID 
UNION ALL 
SELECT 'NULL' AS mgtapproval, 6 AS SchedID 
) 
SELECT APPROVED, REJECT, [NULL] 
FROM (
     SELECT MgtApproval, SchedID, ROW_NUMBER() OVER (PARTITION BY mgtapproval ORDER BY SchedID) AS rn 
     FROM LeaveRequest 
     ) l 
     PIVOT 
     (
     MIN(SchedId) 
     FOR  MgtApproval IN 
       ([APPROVED], [Reject], [Null]) 
     ) as pvt 

更新:

既然你提到你的列實際上是一個bit,你應該使用這個語法:

SELECT [1] AS approved, [0] AS reject, [-1] AS nil 
FROM (
     SELECT COALESCE(MgtApproval, -1) AS MgtApproval, SchedID, ROW_NUMBER() OVER (PARTITION BY mgtapproval ORDER BY SchedID) AS rn 
     FROM LeaveRequest 
     ) l 
     PIVOT 
     (
     MIN(SchedId) 
     FOR  MgtApproval IN 
       ([1], [0], [-1]) 
     ) as pvt 
+0

嗨,感謝您的時間。我試過你的代碼並提示我出錯: Msg 8114,Level 16,State 1,Line 1 將數據類型nvarchar轉換爲int時出錯。 Msg 473,Level 16,State 1,Line 1 在PIVOT運算符中提供了錯誤的值「APPROVED」。 – Yves 2009-07-21 15:56:38