Как создать PIVOT TABLE без суммирования столбца - PullRequest
1 голос
/ 21 июля 2009

Вот мой запрос

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         

1 Ответ

5 голосов
/ 21 июля 2009
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
...