簡體   English   中英

mysql從同一表加入總和

[英]mysql join sum from same table

這是我的桌子:

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

我正在嘗試列出收入最高的用戶列表(TOP列表)。 我是用SUM(收益)GROUP BY的用戶名 ,但我想總結upline_earnings了。

在上表中user1test的上線,因此來自test的所有收入都應計為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

歡迎任何幫助!

謝謝!

我想你想通過匯總表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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM