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
嗨,感謝您的時間。我試過你的代碼並提示我出錯: 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