使用另一列的Column of Group连接两个表

时间:2014-12-16 14:55:19

标签: mysql join left-join outer-join

需要帮助才能使用SUM()函数连接和分组两个表。
表格如下:


DEBIT TABLE                 CREDIT TABLE                
---------------------       ---------------------
CustomerName    Debit       CustomerName    Credit
---------------------       ---------------------
Customer1       200.00      Customer1       100.00
Customer1       300.00      Customer1       100.00
Customer2       100.00      Customer1       100.00
Customer2       600.00      Customer2       200.00
-----------------------     Customer2       300.00
                            Customer2       50.00
                            -----------------------

我需要将两个Join表显示为:


JOIN TABLE(DEBIT CREDIT TABLE)              
------------------------------------------
CustomerName    Debit   Credit  Closing
------------------------------------------
Customer1       500.00  300.00  200.00
Customer2       700.00  550.00  150.00
------------------------------------------

这是我得到的,但没有产生正确的结果:



"SELECT Debit_Tbl.CustomerName, SUM(Debit_Tbl.Debit) as Debit, SUM(Credit_Tbl.Credit) as Credit, SUM(Debit_Tbl.Debit) - SUM(Credit_Tbl.Credit) as Closing from Debit_Tbl LEFT OUTER JOIN Credit_Tbl ON Debit_Tbl.CustomerName = Credit_Tbl.CustomerName GROUP BY Debit_Tbl.debit UNION SELECT Debit_Tbl.CustomerName, SUM(Debit_Tbl.Debit) as Debit, SUM(Credit_Tbl.Credit) as Credit, SUM(Debit_Tbl.Debit) - SUM(Credit_Tbl.Credit) as Closing from Debit RIGHT OUTER JOIN Credit_Tbl ON Debit_Tbl.CustomerName = Credit_Tbl.CustomerName GROUP BY Debit_Tbl.debit"
-------------------------------------------

2 个答案:

答案 0 :(得分:0)

这应该有效:

SELECT customerName,
  debit,
  credit,
  debit-credit AS closing
FROM
  (SELECT d.CustomerName AS customerName,
    SUM(d.debit)         AS debit,
    SUM(c.credit)        AS credit
  FROM debit d
  INNER JOIN credit c
  ON d.CustomerName = c.CustomerName
  )

答案 1 :(得分:0)

您的查询正在两个表之间生成笛卡尔积。相反,使用union all将借方和贷方分成不同的列 - 而不是乘以行数。然后进行聚合:

select customerName, sum(debit) as debit, sum(credit) as credit,
       sum(debit) - sum(credit) as closing
from (select d.customerName, debit as debit, 0 as credit
      from debit d
      union all
      select c.customerName, 0 as debit, credit
      from credit c
     ) cd
group by customerName;