-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4.3.sql
More file actions
60 lines (56 loc) · 1.84 KB
/
4.3.sql
File metadata and controls
60 lines (56 loc) · 1.84 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
/* Show year, month, monthly revenue, and percent of current year. */
SELECT *
FROM adoptions;
SELECT DATE_PART ('year', adoption_date) AS year,
DATE_PART ('month', adoption_date) AS month,
SUM (adoption_fee) AS month_total
FROM adoptions
GROUP BY DATE_PART ('year', adoption_date),
DATE_PART ('month', adoption_date)
ORDER BY year ASC,
month ASC;
SELECT DATE_PART ('year', adoption_date) AS year,
DATE_PART ('month', adoption_date) AS month,
SUM (adoption_fee) AS month_total,
CAST (100 * SUM (adoption_fee)
/ SUM (adoption_fee)
OVER (PARTITION BY DATE_PART ('year', adoption_date))
AS DECIMAL (5, 2)
) AS annual_percent
FROM adoptions
GROUP BY DATE_PART ('year', adoption_date),
DATE_PART ('month', adoption_date)
ORDER BY year ASC,
month ASC;/* Error: column "adoptions.adoption_fee" must appear in the GROUP BY clause or be used in an aggregate function */
SELECT DATE_PART ('year', adoption_date) AS year,
DATE_PART ('month', adoption_date) AS month,
SUM (adoption_fee) AS month_total,
CAST (100 * SUM (adoption_fee) -- Group aggregate SUM
/ SUM ( SUM (adoption_fee)) -- Widnow aggregate SUM
OVER (PARTITION BY DATE_PART('year', adoption_date))
AS DECIMAL (5, 2)
) AS annual_percent
FROM adoptions
GROUP BY DATE_PART('year', adoption_date),
DATE_PART('month', adoption_date)
ORDER BY year ASC,
month ASC;
WITH monthly_grouped_adoptions
AS
(
SELECT DATE_PART ('year', adoption_date) AS year,
DATE_PART ('month', adoption_date) AS month,
SUM (adoption_fee) AS month_total
FROM adoptions
GROUP BY DATE_PART ('year', adoption_date),
DATE_PART ('month', adoption_date)
)
SELECT *,
CAST (100 * month_total
/ SUM (month_total)
OVER (PARTITION BY year)
AS DECIMAL (5, 2)
) AS annual_percent
FROM monthly_grouped_adoptions
ORDER BY year ASC,
month ASC;