2012-09-19 197 views
13

我有2個表格需要根據日期和2個值加在一起。Mysql UNION和GROUP BY

這給了我所有信息的列表 - 罰款。

$query = (SELECT date, debit, credit , note FROM proj3_cash) 
UNION 
(SELECT settle, purch, sale, issue FROM proj3_trades) 
ORDER BY date"; 

現在我需要將這兩個表中每日總計的信息分組。

$query = "(SELECT date, SUM(debit), SUM(credit)FROM proj3_cash GROUP BY date) 
UNION 
(SELECT settle as date, SUM(purch) as debit, SUM(sale) as credit FROM proj3_trades GROUP BY date) 
ORDER BY date"; 

精細,但如果在同一天的東西在每個表中我得到這個:

date  SUM(debit) SUM(credit) 
-------------------------------------- 
2010-12-02 0.00   170.02 
2010-12-02 296449.91  233111.10 

我如何組兩成的同一天?

如果我在最後添加GROUP BY - 我只會得到一個錯誤。或者這應該通過JOIN來完成?

回答

15

你可以做到這一點使用派生表:

SELECT date, SUM(debit), SUM(credit) 
FROM 
(
    SELECT date, debit, credit 
     FROM proj3_cash 
    UNION ALL 
    SELECT settle as date, 
      purch as debit, 
      sale as credit 
     FROM proj3_trades 
) derivedTable 
GROUP BY date 
ORDER BY date 

我已經改變了聯盟UNION ALL,因爲工會將消除這兩個表中發現的重複。