-
Notifications
You must be signed in to change notification settings - Fork 1
/
Ch05.2__PivotingAndUnpivotingData.sql
90 lines (76 loc) · 1.67 KB
/
Ch05.2__PivotingAndUnpivotingData.sql
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
-- Chapter 5: Grouping and Windowing
-- Lesson 2: Pivoting and Unpivoting Data
USE TSQL2012;
GO
/* Pivoting Data */
-- pg 164
WITH PivotData AS
(
SELECT
custid, -- grouping
shipperid, -- spreading
freight -- aggregation
FROM Sales.Orders
)
SELECT custid, [1], [2], [3]
FROM PivotData
PIVOT( SUM(freight) FOR shipperid IN ([1],[2],[3]) ) AS P;
-- pg 165
SELECT custid, [1], [2], [3]
FROM Sales.Orders
PIVOT( SUM(freight) FOR shipperid IN ([1],[2],[3]) ) AS P;
-- http://sqlmag.com/t-sql/pivoting-dynamic-way
DECLARE @SQL AS VARCHAR(MAX)
DECLARE @Columns AS VARCHAR(MAX)
SELECT @Columns =
COALESCE(@Columns+',','')+QUOTENAME(shipperid)
FROM
(
SELECT DISTINCT shipperid
FROM Sales.Orders
) AS B
ORDER BY B.shipperid
SET @SQL = '
WITH PivotData AS
(
SELECT
custid, -- grouping
shipperid, -- spreading
freight -- aggregation
FROM Sales.Orders
)
SELECT
custid,
'+@Columns+'
FROM PivotData
PIVOT
(
SUM(freight)
FOR shipperid
IN ('+@Columns+')
) AS PivotResult
ORDER BY custid';
EXEC(@SQL);
/* Unpivoting Data */
USE TSQL2012;
IF OBJECT_ID('Sales.FreightTotals') IS NOT NULL DROP TABLE Sales.FreightTotals;
GO
DECLARE @SQL AS NVARCHAR(4000);
SET @SQL = 'SELECT ''['' + shipperid + '']'' FROM Sales.Orders; '
WITH PivotData AS
(
SELECT
custid, -- grouping
shipperid, -- spreading
freight -- aggregation
FROM Sales.Orders
)
SELECT *
INTO Sales.FreightTotals
FROM PivotData
PIVOT( SUM(freight) FOR shipperid IN ([1],[2],[3]) ) AS P;
SELECT * FROM Sales.FreightTotals;
-- pg 167
SELECT custid, shipperid, freight
FROM Sales.FreightTotals
UNPIVOT( freight FOR shipperid IN ([1],[2],[3]) ) AS U;