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         
4

1 回答 1

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

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
于 2009-07-21T15:46:44.710 回答