-
Notifications
You must be signed in to change notification settings - Fork 30
/
13 Aggregations using Rollup and Cube in Databricks SQL.sql
61 lines (51 loc) · 1.66 KB
/
13 Aggregations using Rollup and Cube in Databricks SQL.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
SELECT * FROM retail.sales;
SELECT `Sale Date`, `Course`,
sum(`Sale Amount`) AS `Sale Amount`,
count(*) AS `Sale Count`
FROM retail.sales
GROUP BY 1, 2 WITH ROLLUP;
WITH sales_rollup AS (
SELECT `Sale Date`, `Course`,
sum(`Sale Amount`) AS `Sale Amount`,
count(*) AS `Sale Count`
FROM retail.sales
GROUP BY 1, 2 WITH ROLLUP
) SELECT * FROM sales_rollup WHERE `Sale Date` IS NULL;
SELECT `Sale Date`,
sum(`Sale Amount`) AS `Sale Amount`,
count(*) AS `Sale Count`
FROM retail.sales
GROUP BY 1 WITH ROLLUP
ORDER BY 1;
SELECT `Sale Date`,
sum(`Sale Amount`) AS `Sale Amount`,
count(*) AS `Sale Count`
FROM retail.sales
GROUP BY 1 WITH CUBE
ORDER BY 1;
SELECT `Sale Date`, `Course`,
sum(`Sale Amount`) AS `Sale Amount`,
count(*) AS `Sale Count`
FROM retail.sales
GROUP BY 1, 2 WITH CUBE;
WITH sales_cube AS (
SELECT `Sale Date`, `Course`,
sum(`Sale Amount`) AS `Sale Amount`,
count(*) AS `Sale Count`
FROM retail.sales
GROUP BY 1, 2 WITH CUBE
) SELECT * FROM sales_cube WHERE `Sale Date` IS NULL AND `Course` IS NOT NULL
ORDER BY 1, 2;
SELECT * FROM retail.online_retail_v;
-- yyyy-MM, yyyy-MM-dd, Count
-- InvoiceMonth, InvoiceDate, InvoiceCount
-- M/d/yy H:mm -> yyyy-MM-dd
SELECT DISTINCT date_format(to_date(InvoiceDate, 'M/d/yy H:mm'), 'yyyy-MM') AS InvoiceMonth,
to_date(InvoiceDate, 'M/d/yy H:mm') AS InvoiceDate
FROM retail.online_retail_v;
SELECT date_format(to_date(InvoiceDate, 'M/d/yy H:mm'), 'yyyy-MM') AS InvoiceMonth,
to_date(InvoiceDate, 'M/d/yy H:mm') AS InvoiceDate,
count(distinct InvoiceNo) AS InvoiceCount
FROM retail.online_retail_v
GROUP BY 1, 2 WITH ROLLUP
ORDER BY 1, 2;