-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunpivot.sql
48 lines (37 loc) · 959 Bytes
/
unpivot.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
Create Table tblForUnPivot
(
SalesAgent nvarchar(50),
India int,
US int,
UK int
)
Go
Insert into tblForUnPivot values ('David', 960, 520, 360)
Insert into tblForUnPivot values ('John', 970, 540, 800)
Go
SELECT * FROM tblForUnPivot
--Unpivot
SELECT SalesAgent, Country, SalesAmount
FROM tblForUnPivot
UNPIVOT (
SalesAmount FOR Country IN (India, US, UK)
) tbl
--Pivot
SELECT SalesAgent, India, US, UK
FROM (SELECT SalesAgent, SalesCountry, SalesAmount FROM tblProductsSale) AS src
PIVOT (
SUM(SalesAmount) FOR SalesCountry IN ([India], [US], [UK])
) AS tbl
--Reverse Pivot
SELECT SalesAgent, SalesCountry, SalesAmount
FROM (
SELECT SalesAgent, India, US, UK
FROM (SELECT SalesAgent, SalesCountry, SalesAmount FROM tblProductsSale) As src
PIVOT (
SUM(SalesAmount) FOR SalesCountry IN (India,US, UK)
) AS pivot_tbl
) as pivot_tbl
UNPIVOT (
SalesAmount FOR SalesCountry IN (India, US, UK)
) AS unpivot_tbl
SELECT * FROM tblProductsSale