连接MySQL中的表,其中列是相加的

时间:2013-12-07 19:39:44

标签: mysql join

我正在尝试加入3个表。其中两个表格是一列的总和。我想在总和上应用条件,但是我没有用下面的脚本生成我想要的结果。总和不能正确汇总。

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语句来实现它,但它没有正确计算。任何有关如何将这些条件应用于总和列的帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

我已更改为LEFT-JOIN,因为您似乎想要所有帐户列表条目,以及每个帐户的任何相应的费用和佣金总和。因此,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

答案 1 :(得分:0)

您可以使用IF在MySQL中创建条件SUM

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

为了更具可移植性,您应该使用CASE,因为IF不是SQL标准的一部分。我倾向于发现IF更具可读性。