我有两张桌子 - 一张用于每日收入,一张用于每日费用。
每个日期都有一个收入
+------------+---------+
| date | revenue |
+------------+---------+
| 2017-01-04 | 100 |
| 2017-01-05 | 150 |
| 2017-01-06 | 200 |
...
没有,每个日期有一个或多个费用。
+------------+---------+
| date | cost |
+------------+---------+
| 2017-01-04 | 17 |
| 2017-01-04 | 32 |
| 2017-01-06 | 55 |
| 2017-01-07 | 10 |
...
我现在想按月对数据进行分组......结果应该是一个表格,列出了每个月的总收入以及总计费用:
+---------+----------+-------+
| month | revenue | costs |
+---------+----------+-------+
| 2017-01 | 4400,00 | 80,00 |
| 2017-02 | 2100,00 | 70,00 |
| 2017-03 | 5500,00 | 90,00 |
...
我该怎么做?
答案 0 :(得分:1)
我认为这是你的期望。
表格强>
CREATE TABLE T1
(
date datetime,
revenue int
);
CREATE TABLE T2
(
date datetime,
cost int
);
INSERT INTO T1 (date,revenue)
VALUES
('2017-01-04',100),
('2017-01-05',150),
('2017-01-06',200),
('2017-02-06',200);
INSERT INTO T2 (date,cost)
VALUES
('2017-01-04',17),
('2017-01-04',32),
('2017-01-06',55),
('2017-01-07',10),
('2017-02-07',10);
<强>查询强>
SELECT T1.MONTH,revenue,costs FROM
(
SELECT DATE_FORMAT(date, '%Y-%m') AS 'month'
,SUM(revenue) AS 'revenue'
FROM T1
GROUP BY DATE_FORMAT(date, '%Y-%m')
) AS T1
INNER JOIN
(
SELECT DATE_FORMAT(date, '%Y-%m') AS 'month'
,SUM(cost) AS 'costs'
FROM T2
GROUP BY DATE_FORMAT(date, '%Y-%m')
) AS T2
ON T1.month = T2.month
答案 1 :(得分:0)
E.g:
SELECT DATE_FORMAT(date,'%Y-%m') yearmonth
, COALESCE(SUM(CASE WHEN type = 'revenue' THEN amount END),0) revenue
, COALESCE(SUM(CASE WHEN type = 'cost' THEN amount END),0) cost
FROM
( SELECT date, 'revenue' type, revenue amount FROM revenue
UNION ALL
SELECT date, 'cost', cost FROM costs
) x
GROUP
BY yearmonth;