简体   繁体   中英

How do I convert rows to columns that resulted from a CTE?

I have a CTE expression of the following form:

WITH nCTE AS
(
   SELECT *
   FROM 
   TableA X INNER JOIN TableB Y
   ON X.ID = Y.ID
)
SELECT *
FROM
(
   SELECT ...
   FROM nCTE
)
WHERE ...
GROUP BY ...
ORDER BY ...

The results of this query look something like this:

ID   Name   Badge   Type   Value
1   John    Blue    Pre    10
1   John    Blue    Post   20
1   John    Blue    Cur    30
1   John    Green   Pre    50
1   John    Green   Post   30
1   John    Green   Cur    20

I am trying to get the results in the following form:

ID   Name   Badge   Pre   Cur   Post
1    John   Blue    10    20    30
2    John   Green   50    30    20

As I am using a CTE, I am not sure if I can do this in a direct way or I should self-join the result multiple times to get this (this will just make everything look long, ugly and complex). Is there a good way to achieve this?

UPDATE: Trying this returns a NULL value

WITH nCTE AS
(
   SELECT *
   FROM 
   TableA X INNER JOIN TableB Y
   ON X.ID = Y.ID
)
SELECT ID, Name, Badge, [0] AS 'Pre', [1] AS 'Cur', [2] AS 'Post'
FROM
(
    SELECT *
    FROM
    (
       SELECT ...
       FROM nCTE
    )
    WHERE ...
    GROUP BY ...
) Y
PIVOT
(
   MAX(Value)
   FOR Type IN ([0], [1], [2])
) AS PivotTable
ORDER BY ...

While the query itself works, it returns the following:

ID   Name   Badge   Pre     Cur     Post
1    John   Blue    NULL    NULL    NULL
2    John   Green   NULL    NULL    NULL

Any suggestions as to why this is happening?

My bad! Pivoting required the actual values. I was blindly following the example from MSDN. In any case, the following works:

WITH nCTE AS
(
   SELECT *
   FROM 
   TableA X INNER JOIN TableB Y
   ON X.ID = Y.ID
)
SELECT ID, Name, Badge, [Pre] AS 'Pre', [Cur] AS 'Cur', [Post] AS 'Post'
FROM
(
    SELECT *
    FROM
    (
       SELECT ...
       FROM nCTE
    )
    WHERE ...
    GROUP BY ...
) Y
PIVOT
(
   MAX(Value)
   FOR Type IN ([Pre], [Cur], [Post])
) AS PivotTable
ORDER BY ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM