2017-05-31 31 views
0

我有三個表: 計費debitcreditJSO如何使一個聯盟而不是把底部它將把在左側MYSQL

我想總計計費按顧客分組,然後在左側添加總計debitcredit按顧客分組,然後在左側添加總計jso按顧客分組,我不能不要LEFT JOIN,因爲有些客戶在計費debitcredit,在相同JSO

預期輸出:

subsid | debitamt  | debitcredit  | amount  | 
1  | 200   | null    | 100  | 
2  | null   | 500    | 300  | 
3  | 100   | 200    | 300  | 

我嘗試這個查詢,但返回的斑點,我不知道它是否正確。

SELECT 
IF(debitamt = "debitamt", 0, debitamt) as debitamt, 
IF(debitcredit = "debitcredit", 0, debitcredit) as debitcredit, 
IF(amount = "amount", 0, amount) as amount 
from (
    SELECT a.subsid, sum(debitamt) as debitamt, "debitcredit", "amount" FROM 
    new.billing a 
    UNION ALL 
    SELECT b.subsid, "debitamt", sum(debit-credit) as debitcredit, "amount" 
    FROM new.debitcredit b 
    UNION ALL 
    SELECT c.subsid, "debitamt", "debitcredit", sum(amount) as amount FROM 
    new.jso c 
) a group by a.subsid 

非常感謝你。

回答

0

嘗試......糾正你內心的選擇字段與顯示

SELECT 
a.subsid, 
sum(debitamt) as debitamt, 
sum(debitcredit) as debitcredit, 
sum(amount) as amount 
from (
    SELECT a.subsid, sum(debitamt) as debitamt, 0 as debitcredit,0 as amount --only need the column defined in first union FROM 
    new.billing a 
    group by a.subsid 
    UNION ALL 
    SELECT b.subsid,0 , sum(debit-credit) ,0 
    FROM new.debitcredit b 
    group by b.subsid 
    UNION ALL 
    SELECT c.subsid, 0, 0, sum(amount) FROM 
    new.jso c 
    group by c.subsid 
) a group by a.subsid 
+0

非常感謝你。它的工作:)。 –

相關問題