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
APIVOT
仍然需要任何聚合函数,但这个函数保证最多聚合一列。
这是对样本数据的查询,它准确地返回了您想要的内容:
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
更新:
由于您提到您的列实际上是 a 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