-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpivoting.sql
More file actions
46 lines (30 loc) · 1.2 KB
/
Copy pathpivoting.sql
File metadata and controls
46 lines (30 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
-- Pivot
SELECT * FROM
(SELECT p.ProductID, pc.Name, ISNULL(p.color, 'Uncolored') AS Color
FROM SalesLT.ProductCategory AS pc
JOIN SalesLT.Product AS p
ON pc.ProductCategoryID = p.ProductCategoryID
) AS ppc
PIVOT(COUNT(ProductID) FOR Color IN([Red], [Blue], [Black], [Silver], [Yellow], [Grey], [Multi], [Uncolored])) as pvt
ORDER BY Name;
-- UnPivot
-- Create a table of pivoted data
CREATE TABLE #ProductColorPivot
(Name VARCHAR(50), Red INT, Blue INT, Black INT, Silver INT, Yellow INT, Grey INT, Multi INT, Uncolored INT);
INSERT INTO #ProductColorPivot
SELECT * FROM
(SELECT p.ProductID, pc.Name, ISNULL(p.color, 'Uncolored') AS Color
FROM SalesLT.ProductCategory AS pc
JOIN SalesLT.Product AS p
ON pc.ProductCategoryID = p.ProductCategoryID
) AS ppc
PIVOT(COUNT(ProductID) FOR Color IN([Red], [Blue], [Black], [Silver], [Yellow], [Grey], [Multi], [Uncolored])) as pvt
ORDER BY Name;
-- now unpivot the table
SELECT Name, Color, ProductCount
FROM
(SELECT Name, [Red], [Blue], [Black], [Silver], [Yellow], [Grey], [Multi], [Uncolored]
FROM #ProductColorPivot) AS pcp
UNPIVOT
(ProductCount FOR Color IN ([Red], [Blue], [Black], [Silver], [Yellow], [Grey], [Multi], [Uncolored])) AS ProductCounts
ORDER BY Name;