简体   繁体   中英

Joining two table with SUM of Column and Group by another column

Need help to join and group with SUM() function two tables.
The Tables are as under:


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
                            -----------------------

I need to show the two Join table as:


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

This is as far as I am getting but doesn't yield the right result:



"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"
-------------------------------------------

This should work:

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
  )

Your query is producing a cartesian product between the two tables. Instead, use union all to separate the debits and credits into separate columns -- without multiplying the number of rows. Then do the aggregation:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM