File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
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 ;
You can’t perform that action at this time.
0 commit comments