Byron Whitlock
Byron Whitlock

Reputation: 53851

Pivot Queries in a UNION

Pivon queries, love em. Turn rows into columns. I need to do a pivot query on the union of 3 other queries. How do I structure this?

I already know the names of the fields in the rows I want to transform but where do I put the pivot statement so it works?

Upvotes: 1

Views: 3590

Answers (1)

Remus Rusanu
Remus Rusanu

Reputation: 294237

Use a derived table:

SELECT ...
 FROM (
   SELECT ...
    FROM ...
   UNION ALL
   SELECT ...
    FROM ...
   ...)
PIVOT ...

or a CTE:

WITH cte AS (
  SELECT ...
    FROM ...
   UNION ALL
   SELECT ...
    FROM ...
   ...)
SELECT ...
  FROM cte
  PIVOT ...

Upvotes: 5

Related Questions