Mysql UNION和GROUP BY

时间:2012-09-19 08:02:40

标签: mysql join group-by union

我需要根据日期和2个值添加2个表。

这给了我所有信息的列表 - 很好。

$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来完成?

1 个答案:

答案 0 :(得分:17)

您可以使用派生表来实现此目的:

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更改为UNION ALL,因为union将消除两个表中找到的重复项。