每个用户的SQL计数引用

时间:2018-10-23 18:31:56

标签: sql

我的查询:

SELECT COUNT(referrer) as refs, SUM(amount) as total, contracts.id, userid, fine
FROM contracts
JOIN users ON contracts.userid = users.id
WHERE active = 1
GROUP BY userid

我的用户表:

id | username | referrer (int)
1  | test     | 2
2  | drekorig | 
3  | maximili | 2

我的合约表:

id ! userid | amount | fine       | active
1  | 1      | 50     | 23/10/2018 | 1
2  ! 2      | 120    | 24/10/2018 | 1
3  | 2      | 150    | 24/10/2018 | 1

如何获取每个用户的推荐人数?我的查询实际上获取的是合同数量...

预期结果:

refs | total | id | userid | fine
0    | 0     | 1  | 1      | 23/10/2018
2    | 270   | 2  | 2      | 24/10/2018

1 个答案:

答案 0 :(得分:0)

http://sqlfiddle.com/#!9/0a464d/5

SELECT r.count as refs, 
   SUM(amount) as total, 
   MAX(c.id), 
   u.id, 
   MAX(fine)
FROM users u
LEFT JOIN 
   (SELECT referrer, COUNT(*) `count`
    FROM users
    GROUP BY referrer
 ) r
ON u.id = r.referrer
JOIN contracts c 
ON c.userid = u.id
WHERE active = 1
GROUP BY u.id