2017-02-06 92 views
0

我在mysql中有三個表,數據如下,我想知道如何得到以下輸出。我不知道我的編碼有什麼問題?在交叉表上的mysql計算

select 
    rev.memberid, 
    (sum(rev.earned)/rule.revperpoint) - sum(redeem.redeempoint) as bal 
from rev 
left join rule on rev.rulename = rule.rulename 
inner join redeem on rev.memberid = redeem.memberid 
group by rev.memberid; 

table1的規則

rulename revperpoint 
CNY  2 
NY  1 

表2修訂版

memberid earned rulename 
37638899 500.50 CNY 
37638899 400.50 CNY 
25264833 300.50 CNY 
2526833 600.50 CNY 

表3贖回

memberid redeempoint 
25264833 100.00 
25264833 50.00 

預期輸出

memberid bal 
25264833 300.50 
37638899 450.50 
+0

一般評論:** OUTER JOIN **之後的INNER JOIN **取消其效果。 –

回答

0

根據您所期望的結果,在表rev 4號線應該是

25264833 600.50 CNY 

在這裏,你不應該使用inner join,因爲它只會retrive記錄下哪些MEMBERID是25264833,試試這個:

select 
    rev.memberid, 
    (sum(rev.earned)/rule.revperpoint) - coalesce(redeem.redeempoint, 0) as bal 
from rev 
left join rule on rev.rulename = rule.rulename 
left join (select memberid, sum(redeem.redeempoint) as redeempoint from redeem group by memberid) redeem on rev.memberid = redeem.memberid 
group by rev.memberid; 

demo這裏。

+0

非常感謝你! – chancj