- Notifications
You must be signed in to change notification settings - Fork 849
/
Copy pathanalytics-PIVOT-and-UNPIVOT-functions.sql
73 lines (61 loc) · 2.01 KB
/
analytics-PIVOT-and-UNPIVOT-functions.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
REM Script: Analytics - PIVOT and UNPIVOT functions
REM SQL from the KISS (Keep It Simply SQL) Analytic video series by Developer Advocate Connor McDonald. This script demonstrates the PIVOT and UNPIVOT functions.
Run this script standalone, or take it as part of the complete Analytics class at https://tinyurl.com/devgym-classes
select to_char(trunc(s.time_id,'Q'),'MON') quarter,
prod_category,
count(*)
fromsh.sales s,
sh.products p
wheres.prod_id=p.prod_id
ands.time_Id>=date'2000-01-01'
ands.time_Id<date'2001-01-01'
group byp.prod_category,
to_char(trunc(s.time_id,'Q'),'MON')
order by2,to_date(to_char(trunc(s.time_id,'Q'),'MON'),'MON');
select prod_category,jan,apr,jul,oct
from (
select to_char(trunc(s.time_id,'Q'),'MON') quarter,
prod_category
fromsh.sales s,
sh.products p
wheres.prod_id=p.prod_id
ands.time_Id>=date'2000-01-01'
ands.time_Id<date'2001-01-01'
)
pivot ( count(*) for quarter in
( 'JAN'as jan,'APR'as apr,'JUL'as jul,'OCT'as oct ) )
order by1;
droptable pivoted_sales purge;
createtablepivoted_salesas
select prod_category,jan,apr,jul,oct
from (
select to_char(trunc(s.time_id,'Q'),'MON') quarter,
prod_category
fromsh.sales s,
sh.products p
wheres.prod_id=p.prod_id
ands.time_Id>=date'2000-01-01'
ands.time_Id<date'2001-01-01'
)
pivot ( count(*) for quarter in
( 'JAN'as jan,'APR'as apr,'JUL'as jul,'OCT'as oct ) )
order by1;
select prod_category, quarter, quantity
from pivoted_sales
unpivot
( quantity for quarter in (JAN,APR,JUL,OCT) )
order by1,to_date(quarter,'MON');
update pivoted_sales
set oct =null
where prod_category ='Hardware';
commit
select prod_category, quarter, quantity
from pivoted_sales
unpivot
( quantity for quarter in (JAN,APR,JUL,OCT) )
order by1,to_date(quarter,'MON');
select prod_category, quarter, quantity
from pivoted_sales
unpivot include nulls
( quantity for quarter in (JAN,APR,JUL,OCT) )
order by1,to_date(quarter,'MON');