我有这两张桌子。
表INCOMES
ID |有效|收入| DATE
1 123 12 2017-03-01
2 99 44 2017年3月1日
3 66 44 2017年4月1日
4 66 44 2017年4月1日
5 66 44 2017年5月1日
表COSTES
ID |成本| DATE
1 123 2017-04-01
2 99 2017-04-01
3 77 2017-05-01
4 33 2017-05-01
5 66 2017-06-01
我需要得到SUM(有效)[整月的总和,例如2017-03是123 + 99],SUM(收入)[整月的总和,例如2017-03是12 + 44] ,SUM(COSTS)[整月的总和,例如2017-03为0 + 0,beucase当月没有成本]和DATE VALUES orderer by DATE。 结果应该是这样的:
结果查询
有效|收入|成本| DATE
222 56 0 2017-03
132 88 22 2017-04
66 44 22中文
0 0 66 2017-06
我已经将QUERY分开了
SELECT
SUM(validated) AS 'validated',
SUM(revenue) AS 'revenue',
DATE_FORMAT(Date, '%Y-%m') AS Date
FROM incomes WHERE date LIKE '%2017%'
GROUP BY(DATE_FORMAT(Date, '%Y-%m'));
SELECT
SUM(validacion) AS 'costes',
DATE_FORMAT(Date, '%Y-%m') AS Date
FROM costes WHERE date LIKE '%2017%'
GROUP BY(DATE_FORMAT(Date, '%Y-%m'));
请帮助我们。
答案 0 :(得分:1)
SELECT
SUM(validated) AS 'validated',
SUM(revenue) AS 'revenue',
SUM(COS.COSTS) COSTS,
DATE_FORMAT(Date, '%Y-%m') AS Date
FROM
incomes INC
INNER JOIN
costes COS ON DATE_FORMAT(INC.Date, '%Y-%m') = DATE_FORMAT(COS.Date, '%Y-%m')
GROUP BY DATE_FORMAT(INC.Date, '%Y-%m')
尝试以上查询。
答案 1 :(得分:0)
您需要使用UNION语句来实现此目标。
SELECT调用需要包含相同的列名。因此SGBD会创建一个临时表(我称之为“union_tb”),因此您可以根据需要使用它。
看看:
SELECT SUM(union_tb.validated) AS validated
, SUM(union_tb.revenue) AS revenue
, SUM(union_tb.costes) AS costes
, union_tb.date
FROM (
SELECT SUM(validated) AS 'validated'
, 0 AS 'costes'
, SUM(revenue) AS 'revenue'
, DATE_FORMAT(DATE, '%Y-%m') AS 'date'
FROM incomes
WHERE YEAR(DATE) = 2017
GROUP BY(DATE_FORMAT(DATE, '%Y-%m'))
UNION
SELECT 0 AS 'validated'
, SUM(validacion) AS 'costes'
, 0 AS 'revenue'
, DATE_FORMAT(DATE, '%Y-%m') AS 'date'
FROM costes
WHERE YEAR(DATE) = 2017
GROUP BY(DATE_FORMAT(DATE, '%Y-%m'))
) AS union_tb
WHERE 1
GROUP BY union_tb.date ;