Syntax:
;WITH <cte_name> AS
(
SELECT
<grouping_column>,
<spreading_column>,
<aggregation_column>
FROM <source_table>
)
SELECT <select_list>
FROM <cte_name>
PIVOT( <aggregate_function>(<aggregation_column>)
FOR <spreading_column> IN (<distinct_spreading_values>) ) AS <alias>;
Example: Display the monthly totals per customer side-by-side for a year.
SELECT ct.CustomerID,
DATENAME(month, transactiondate) [MonthName],
SUM(ct.TransactionAmount) [2013MonthlyTotal]
FROM Sales.CustomerTransactions ct
WHERE ct.TransactionDate BETWEEN '2013-01-01' AND '2013-12-31'
AND ct.TransactionTypeID = 1
AND ct.CustomerID = 801
GROUP BY ct.CustomerID,
DATENAME(month, transactiondate),
DATEPART(month, transactiondate)
ORDER BY DATEPART(month, transactiondate);
;WITH PivotData
AS (SELECT ct.CustomerID,
DATENAME(month, transactiondate) [MonthName],
ct.TransactionAmount [2013MonthlyTotal]
FROM Sales.CustomerTransactions ct
WHERE ct.TransactionDate BETWEEN '2013-01-01' AND '2013-12-31'
AND ct.TransactionTypeID = 1)
SELECT *
FROM PivotData pd PIVOT(SUM([2013MonthlyTotal]) FOR MonthName
IN([January],
[February],
[March],
[April],
[May],
[June],
[July],
[August],
[September],
[October],
[November],
[December])) AS P
ORDER BY CustomerID;
