SQL 统计两个表的数据,按同一日期分组

时间:2023-03-08 17:32:43
SQL 统计两个表的数据,按同一日期分组

思路:把两个表的数据按日期整合到临时表在按日期分组,求和。

例子:

SELECT t.dateTime AS '日期',SUM(t.money) AS '表1利息',SUM(t.interest) AS '表2利息'
FROM(
SELECT DATE_FORMAT(date,'%Y-%m-%d') AS dateTime,SUM(money) AS money,'0' AS interest
FROM Table1
GROUP BY DATE_FORMAT(date,'%Y-%m-%d')
UNION
SELECT DATE_FORMAT(date,'%Y-%m-%d') AS dateTime, '0' AS money,SUM(interest) AS interest
FROM Table2
GROUP BY DATE_FORMAT(date,'%Y-%m-%d')
) t
GROUP BY t.dateTime;