Skip to content

Commit 7140951

Browse files
authored
Create 4th-presentation-query.sql
1 parent d025940 commit 7140951

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

4th-presentation-query.sql

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/* ---------- Query 4 - Film rental distribution by category ---------- */
2+
3+
WITH t1 AS (SELECT c.customer_id,
4+
p.amount,
5+
DATE_TRUNC('month', p.payment_date) AS payment_date,
6+
p.rental_id
7+
FROM customer AS c
8+
JOIN payment AS p
9+
ON c.customer_id = p.customer_id),
10+
11+
t2 AS (SELECT t1.customer_id,
12+
t1.payment_date,
13+
SUM(t1.amount) AS total_amtpaid,
14+
LEAD(SUM(t1.amount)) OVER(w) AS lead_num,
15+
LEAD(SUM(t1.amount)) OVER(w) - SUM(t1.amount) AS lead_dif,
16+
CASE
17+
WHEN LEAD(SUM(t1.amount)) OVER(w) - SUM(t1.amount) < 0 THEN 0
18+
WHEN LEAD(SUM(t1.amount)) OVER(w) - SUM(t1.amount) >= 0 THEN 1
19+
END AS progress
20+
FROM t1
21+
JOIN rental AS r
22+
ON r.rental_id = t1.rental_id
23+
AND t1.customer_id = r.customer_id
24+
GROUP BY 1, 2
25+
WINDOW w AS (PARTITION BY t1.customer_id ORDER BY DATE_TRUNC('month', t1.payment_date)))
26+
27+
SELECT t2.payment_date,
28+
COUNT(*) AS total_count,
29+
SUM(t2.progress) AS progress_bymon,
30+
COUNT(*) - SUM(t2.progress) AS regress_bymon
31+
FROM t2
32+
WHERE t2.progress IS NOT NULL
33+
GROUP BY 1
34+
ORDER BY 1;

0 commit comments

Comments
 (0)