如何从两个表中按月汇总值?
我有两张桌子:
1)costs_1
-id
-total
-updated_at(timestamp)
2)costs_2
-id
-total_1
-updated_at_1(timestamp)
结果表需要有下一列:
-total
-total_1
-month
例如,如果我有一个表,我会进行下一个查询:
SELECT SUM(total), MONTH(updated_at), YEAR(updated_at) FROM product_sale GROUP BY MONTH(updated_at), YEAR(updated_at) ORDER by MONTH(updated_at)
答案 0 :(得分:1)
我相信你想要这样的东西。
SELECT t1.y year,
t1.m month,
t1.total,
t2.total
FROM
(
SELECT YEAR(updated_at) y,
MONTH(updated_at) m,
SUM(total) total
FROM costs_1
GROUP BY YEAR(updated_at), MONTH(updated_at)
) t1
JOIN
(
SELECT YEAR(updated_at_1) y,
MONTH(updated_at_1) m,
SUM(total_1) total
FROM costs_2
GROUP BY YEAR(updated_at_1), MONTH(updated_at_1)
) t2 ON t1.y = t2.y and t1.m = t2.m
但是,在此解决方案中,如果costs_1
或costs_2
没有任何月份记录,您将错过一个月。如果你想要FULL JOIN,你必须使用两个OUTER JOINS在mysql中模拟它,如下所示:
SELECT t1.y year,
t1.m month,
COALESCE(t1.total, 0),
COALESCE(t2.total, 0)
FROM
(
SELECT YEAR(updated_at) y,
MONTH(updated_at) m,
SUM(total) total
FROM costs_1
GROUP BY YEAR(updated_at), MONTH(updated_at)
) t1
LEFT JOIN
(
SELECT YEAR(updated_at_1) y,
MONTH(updated_at_1) m,
SUM(total_1) total
FROM costs_2
GROUP BY YEAR(updated_at_1), MONTH(updated_at_1)
) t2 ON t1.y = t2.y and t1.m = t2.m
UNION
SELECT t2.y year,
t2.m month,
COALESCE(t1.total, 0),
COALESCE(t2.total, 0)
FROM
(
SELECT YEAR(updated_at) y,
MONTH(updated_at) m,
SUM(total) total
FROM costs_1
GROUP BY YEAR(updated_at), MONTH(updated_at)
) t1
RIGHT JOIN
(
SELECT YEAR(updated_at_1) y,
MONTH(updated_at_1) m,
SUM(total_1) total
FROM costs_2
GROUP BY YEAR(updated_at_1), MONTH(updated_at_1)
) t2 ON t1.y = t2.y and t1.m = t2.m
答案 1 :(得分:0)
试试这个:
SELECT total, total_1, MONTHNAME(costs_1.updated_at) from costs_1 INNER JOIN costs_2
ON
MONTH(costs_1.updated_at)=MONTH(costs_2.updated_at)