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