我想amount
对给定月份的列以及上个月的总数求和。目前第一个月的总工程量,但此后每个月都高出至少 2 个数量级。
SELECT month, year, total, previous_month, previous_year, previous_total FROM (
SELECT MONTH(p1.start_date) AS month,
YEAR(p1.start_date) AS year,
SUM(p1.amount) AS total,
SUM(p2.amount) AS previous_total,
MONTH(DATE_SUB(p1.start_date, INTERVAL 1 MONTH)) AS previous_month,
YEAR(DATE_SUB(p1.start_date, INTERVAL 1 MONTH)) AS previous_year
FROM trackings p1
LEFT JOIN trackings p2 ON EXTRACT(YEAR_MONTH FROM DATE_SUB(p1.start_date, INTERVAL 1 MONTH)) = EXTRACT(YEAR_MONTH FROM p2.start_date)
GROUP BY EXTRACT(YEAR_MONTH FROM p1.start_date)
) AS p3;
相关问题:我做同样的DATE_SUB
3次。有没有办法清理日期相关部分以提高效率?