I'm looking for a possible solution that will give me TOP 3 users from users table who are ordered based on the turnover they made.
So here is my table schema for users and transactions table.
users TABLE
id inviter_id
1 1
2 1
3 1
4 1
5 2
6 3
7 5
8 6
9 1
10 3
11 9
12 1
13 5
14 7
15 11
EXPLANATION : The id represents user's unique ID and inviter_id represents the ID that invited the user.
transactions TABLE
id payer _id amount
1 2 200
2 2 100
3 2 50
4 2 10
5 3 400
6 4 200
7 5 100
8 6 50
9 7 100
10 8 50
11 9 50
12 10 100
13 11 400
14 2 200
15 2 100
16 2 50
17 2 10
18 4 500
Here payer_id represents the users in users table.
Desired Output :
user_id turnover
//ID 1 should not be included in this table.
2 100 //ID 5 in `users` is referral of ID 2 so summing whatever ID 5 from `transactions` table using `payer_id` column we get : 100 (Sme process for other rows too)
3 150 //ID3's referrals : 6,10 | 50+100
4 0 //ID4's invited no one
5 100 //ID5's referrals : 7,13 | 100
6 50 //ID 6's referrals : 8 | 50
7 100 // ID 7's referrals : 14 | 0 (No rows for ID 14 in transactions table)
8 0 //No referrals invited
9 400 //ID9's referrals : 11 | 400
10 0 //No referrals invited
11 0 //ID11's referrals : 14 | 0 (No rows in txn table)
12 0 //No referrals invited
13 0 //No referrals invited
14 0 //No referrals invited
15 0 //No referrals invited
FIRST let me explain how I calculate turnover :
For each id from users table, Let's take id:1 as example. I check the 'inviter_id' column for 2. So whoever has the value as 2 in inviter_id column, those ids are considered as id 2's referral.
So I need the sum of amount all the referrals of id 2 has paid. Similarly for other ids and they should be sorted by the highest turnover.
What I tried so far : here is my code.
select u.id AS user_id, u.address AS address, SUM(turnover) AS turnover
from users u left join
(select ur.id, ur.inviter_id, SUM(mt.userTurnover) as turnover
from users ur left join
(select m.payer_id, SUM(m.amount) as userTurnover
from matrix m where m.created >= $content_start AND m.type = 'escrow'
group by m.payer_id
) mt
on mt.payer_id = ur.id
where ur.created >= $content_start
group by ur.inviter_id
) ui
on ui.inviter_id = u.id
WHERE u.id != 1 AND u.id != 2 AND u.id != 3 AND u.id != 4
group by u.id
order by turnover desc LIMIT 10;
I'm getting the sum of amounts of the user itself instead of the user's each and every referral's paid amount.
user_id7 and 8 are taken from? user 7 invites user 14 which have no payments, user 8 invites nobody.id=1and not exasts for all another? (08aa51cef61d0945d035e36e2c3405e3)