mysql从同一个表加入sum

时间:2013-12-30 01:25:27

标签: mysql sql join group-by sum

这是我的表:

http://i.stack.imgur.com/65LHJ.png

我正在尝试列出收入最高的用户列表(TOP列表)。 我使用 SUM(收入) GROUP BY用户名,但我想 SUM upline_earnings 。< / p>

上表 user1 测试的上线,因此测试的所有收入都应计为 user1 赚钱。

这是我的代码:

SELECT COUNT (a.id) as total,
             (SUM(CASE WHEN b.upline=a.username THEN b.up_earnings ELSE 0 END)+SUM(a.earnings)) as tot_earnings,
             SUM(a.dls) as tot_dls,
             a.username
FROM logs a left join logs b ON a.username=b.upline
GROUP BY a.username ORDER BY tot_earnings DESC

但它不起作用!看起来表A的结果将重复:http://i.stack.imgur.com/Mefht.png

欢迎任何帮助!

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您希望在执行username之前按join汇总表格。如果我理解你要做什么,这可能是查询:

SELECT l.username, count(*) as total_uplines,
       coalesce(sum(b.up_earnings), 0) + l.earnings as tot_earnings,
       l.tot_dls
FROM (select l.username, sum(l.earnings) as earnings,
             sum(l.dls) as tot_dls
      from logs l
      group by l.username
     ) l left join
     logs b
     ON l.username = b.upline
GROUP BY l.username, l.earnings, l.tot_dls
ORDER BY tot_earnings DESC;