-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueries.txt
More file actions
106 lines (85 loc) · 2.58 KB
/
Queries.txt
File metadata and controls
106 lines (85 loc) · 2.58 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
Question #1 - Family Movies with the Highest Rental Rate
WITH t1 AS
(
SELECT i.film_id, COUNT(*) movie_rental_count
FROM inventory i
JOIN rental r
ON r.inventory_id = i.inventory_id
GROUP BY 1
),
t2 AS
(
SELECT f.film_id, f.title, c.name
FROM film f
JOIN film_category fc
ON fc.film_id = f.film_id
JOIN category c
ON fc.category_id = c.category_id
)
SELECT t2.name, SUM(t1.movie_rental_count)
FROM t1
JOIN t2
ON t1.film_id = t2.film_id
GROUP BY 1
HAVING t2.name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family', 'Music')
ORDER BY 2 DESC
Question #2 - Family Movies Quartile Rental Rate
WITH t1 AS
(
SELECT c.name, NTILE(4) OVER (ORDER BY f.rental_duration) standard_quartile
FROM category c
JOIN film_category fc
ON c.category_id = fc.category_id
JOIN film f
ON f.film_id = fc.film_id
)
SELECT t1.name, t1.standard_quartile, COUNT(*) AS count
FROM t1
WHERE t1.name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family', 'Music')
GROUP BY 1,2
ORDER BY 1,2
Question #3 - Top 10 Paying Customers on Monthly Basis
SELECT
CONCAT(c.first_name, ' ', c.last_name) full_name,
DATE_TRUNC('month', p.payment_date) AS month,
COUNT(*) monthly_payment_count,
SUM(p.amount) monthly_payment_total
FROM customer c
JOIN payment p
ON p.customer_id = c.customer_id
GROUP BY 1,2
ORDER BY 4 DESC
LIMIT 10
Question #4 - Monthly Difference of Top 10 Paying Customers
WITH t1 AS
(
SELECT
CONCAT(c.first_name, ' ', c.last_name) full_name,
DATE_TRUNC('month', p.payment_date) AS month,
COUNT(*) monthly_payment_count,
SUM(p.amount) monthly_payment_total,
c.customer_id
FROM customer c
JOIN payment p
ON p.customer_id = c.customer_id
GROUP BY 1,2,5
),
t2 AS
(
SELECT customer_id, SUM(amount) total_amount
FROM payment
GROUP BY 1
ORDER BY 2 DESC
LIMIT 10
)
SELECT
t1.full_name,
t1.month,
t1.monthly_payment_total,
COALESCE(LEAD(t1.monthly_payment_total) OVER(PARTITION BY t1.full_name ORDER BY t1.monthly_payment_total), 0) AS lead,
COALESCE((LEAD(t1.monthly_payment_total) OVER(PARTITION BY t1.full_name ORDER BY t1.monthly_payment_total)) - t1.monthly_payment_total, 0)
AS monthly_payment_difference
FROM t1
JOIN t2
ON t1.customer_id = t2.customer_id
ORDER BY 1