tags:

views:

73

answers:

1

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?

+2  A: 

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 ...
Remus Rusanu