| How to
combine CTE with PIVOT? |
|
Execute the following
script in Query Editor to create a monthly tabulation of purchase
orders by vendors:
USE AdventureWorks;
WITH cteMonthlyPurchaseOrders
AS(
SELECT
VendorID,
OrderMonth=DATEPART(m, OrderDate),
SubTotal
FROM Purchasing.PurchaseOrderHeader
WHERE VendorID > 50
AND Year(OrderDate) = 2003
)
SELECT Vendor = [Name], X.*
FROM cteMonthlyPurchaseOrders po
PIVOT (SUM(SubTotal)
FOR OrderMonth In (
[1],[2],[3],[4],[5],[6],
[7],[8],[9],[10],[11],[12])) As X
JOIN Purchasing.Vendor v
ON X.VendorID=v.VendorID
ORDER BY Vendor
GO
|
| The Best SQL Server
2005 Training in the World |
|