-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQL Server GROUPING SETS.sql
More file actions
112 lines (100 loc) · 2.08 KB
/
Copy pathSQL Server GROUPING SETS.sql
File metadata and controls
112 lines (100 loc) · 2.08 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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
-- create new table
SELECT
b.brand_name AS brand,
c.category_name AS category,
p.model_year,
ROUND(SUM(quantity * i.list_price * (1 - discount)), 0) AS sales
INTO sales.sales_summary
FROM sales.order_items i
INNER JOIN production.products p ON p.product_id = i.product_id
INNER JOIN production.brands b ON b.brand_id = p.brand_id
INNER JOIN production.categories c ON c.category_id = p.category_id
GROUP BY b.brand_name, c.category_name, p.model_year
ORDER BY b.brand_name, c.category_name, p.model_year;
GO
SELECT * FROM sales.sales_summary
ORDER BY brand, category, model_year;
GO
SELECT
brand,
category,
SUM (sales) sales
FROM sales.sales_summary
GROUP BY brand, category
ORDER BY brand, category;
GO
SELECT
brand,
SUM(sales) sales
FROM sales.sales_summary
GROUP BY brand
ORDER BY brand;
GO
SELECT
category,
SUM(sales) sales
FROM sales.sales_summary
GROUP BY category
ORDER BY category;
GO
SELECT
SUM(sales)
FROM sales.sales_summary;
-- union all
SELECT
brand,
category,
SUM(sales) sales
FROM sales.sales_summary
GROUP BY brand, category
UNION ALL
SELECT
brand,
NULL,
SUM(sales) sales
FROM sales.sales_summary
GROUP BY brand
UNION ALL
SELECT
NULL,
category,
SUM(sales) sales
FROM sales.sales_summary
GROUP BY category
UNION ALL
SELECT
NULL,
NULL,
SUM(sales) sales
FROM sales.sales_summary
ORDER BY brand, category;
-- SQL Server GROUPING SETS
SELECT
brand,
category,
SUM(sales) sales
FROM sales.sales_summary
GROUP BY
GROUPING SETS (
(brand, category),
(brand),
(category),
()
)
ORDER BY brand, category;
GO
SELECT
GROUPING(brand) grouping_brand,
GROUPING(category) grouping_category,
brand,
category,
SUM(sales) sales
FROM sales.sales_summary
GROUP BY
GROUPING SETS (
(brand, category),
(brand),
(category),
()
)
ORDER BY brand, category;