2013-12-07 33 views
0

我想加入3個表格。其中兩個表格我正在對一列進行總結。我想對這些總和應用條件,但是我沒有用下面的腳本產生我想要的結果。總和不正確。在MySQL中加入列的列表

SELECT 
account_list.Account_ID, 
account_list.Account_Name, 
account_list.Short_Name, 
account_list.Trader, 
account_list.Status, 
account_list.Notes, 
sum(account_commissions.Commission), 
sum(connection_cost.Monthly_Cost) 
FROM 
account_commissions 
Join 
connection_cost 
ON 
account_commissions.Account_ID = connection_cost.Account_ID 
AND 
connection_cost.Cost_Date > '2013-06-01' 
AND 
account_commissions.TDate > '2013-06-01'  
Right Join 
account_list 
ON 
account_list.Account_ID = connection_cost.Account_ID 
WHERE 
account_list.status = 'Active' 
GROUP BY 
Account_ID; 

我要上資金的條件是:

sum account_commissions.Commission where account_commissions.TDate > '2013-06-01 Group BY Account_ID 

sum connection_cost.Monthy_Cost where connection_cost.Date > '2013-06-01' Group BY Account_ID. 

我試圖做到這一點使用上述AND陳述,但沒有正確計算。任何幫助如何應用這些條件的總和列將不勝感激。

回答

1

我已經更改爲左連接,因爲看起來您想要所有帳戶列表條目以及每個帳戶的成本和佣金的任何相應總和。因此,JOIN基於每個表的sum()單獨計算,但是按帳戶分組,然後再加入主帳戶列表表。

SELECT 
     AL.Account_ID, 
     AL.Account_Name, 
     AL.Short_Name, 
     AL.Trader, 
     AL.Status, 
     AL.Notes, 
     coalesce(preSumCC.CC_Costs, 0) as MonthlyCosts, 
     coalesce(preSumComm.AC_Commission, 0) as Commissions 
    FROM 
     account_list AL 
     LEFT JOIN (SELECT CC.Account_ID, 
          SUM(CC.Monthly_Cost) CC_Costs 
         FROM 
          connection_cost CC 
         where 
          CC.Cost_Date > '2013-06-01' 
         group by 
          CC.Account_ID) preSumCC 
      ON AL.Account_ID = preSumCC.Account_ID 

     LEFT JOIN (select AC.Account_ID, 
          SUM(AC.Commission) AC_Commission 
         FROM 
          account_commissions AC 
         where 
          AC.TDate > '2013-06-01' 
         group by 
          AC.Account_ID) preSumComm 
      ON AL.Account_ID = preSumComm.Account_ID 
+0

這就是它。產生我期待的結果。謝謝。 – Stevenyc091

0

可以使用IF在MySQL中建立一個條件SUM

SUM(IF(account_commisions.TDate >'2013-01-01',account_commissions_Commission, 0)) 

更便攜,你應該使用CASE,爲IF不是SQL標準的一部分。我傾向於發現IF更具可讀性。

+0

使用如果它現在按照日期條件求和,但它似乎並沒有將彙總條件應用於彙總語句,因爲它仍然無法正確計算。根據給定的開始日期,我需要總計由Account_ID分組的佣金。 – Stevenyc091

+0

@Steve你是完整的'SELECT'如果分組的方式,所以你應該沒問題。請以你得到的和你的期望爲例來更新你的答案。 –