3
3
# Find out the current balance of all users and
4
4
# check wheter they have breached their credit limit (If their current credit is less than 0).
5
5
6
+
7
+
8
+ # First sulution is SUM the two types transaction in SELECT statement
9
+ SELECT user_id,user_name,
10
+
11
+ # use IFNULL( ,0) because it could be a situation that the customer has no transaction
12
+ IFNULL(SUM (CASE WHEN a .user_id = b .paid_by THEN - amount ELSE amount END),0 )+ a .credit as credit,
13
+ CASE WHEN IFNULL(SUM (CASE WHEN a .user_id = b .paid_by THEN - amount ELSE amount END),0 )>= - a .credit THEN " No" ELSE " Yes" END as credit_limit_breached
14
+ FROM Users as a
15
+ LEFT JOIN Transactions as b
16
+
17
+ # Becareful there is no user_id in Transactions table
18
+ ON a .user_id = b .paid_by OR a .user_id = b .paid_to
19
+ GROUP BY a .user_id ;
20
+
21
+
22
+
23
+
24
+
25
+ # Second sulution is SUM the two types transaction by making two extra tables
6
26
SELECT u .user_id AS USER_ID,
7
27
u .user_name AS USER_NAME,
8
28
(u .credit - IFNULL(a .c_munis ,0 ) + IFNULL(b .c_plus ,0 ) )AS CREDIT,
29
+
30
+ # 'Yes' means excessed (breached their credit limit)
9
31
IF(u .credit - IFNULL(a .c_munis ,0 ) + IFNULL(b .c_plus ,0 )< 0 ,' Yes' ,' No' ) AS CREDIT_LIMIT_BREACHED
10
32
FROM users u
11
33
LEFT JOIN
@@ -22,14 +44,6 @@ ON b.paid_to = u.user_id
22
44
23
45
24
46
25
- SELECT user_id,user_name,
26
- IFNULL(SUM (CASE WHEN a .user_id = b .paid_by THEN - amount ELSE amount END),0 )+ a .credit as credit,
27
- CASE WHEN IFNULL(SUM (CASE WHEN a .user_id = b .paid_by THEN - amount ELSE amount END),0 )>= - a .credit THEN " No" ELSE " Yes" END as credit_limit_breached
28
- FROM Users as a
29
- LEFT JOIN Transactions as b
30
- ON a .user_id = b .paid_by OR a .user_id = b .paid_to
31
- GROUP BY a .user_id ;
32
-
33
47
34
48
35
49
with spent as (
@@ -57,6 +71,8 @@ order by user_id
57
71
58
72
59
73
74
+
75
+
60
76
with cte as
61
77
(select q .user_id , sum (q .net_amt ) as trans_total from
62
78
(select paid_by as user_id, - 1 * sum (amount) as net_amt
0 commit comments