1

我想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_SUB3次。有没有办法清理日期相关部分以提高效率?

示例:http ://sqlfiddle.com/#!2/3013a/1

4

1 回答 1

2

认为问题是您在连接中多次计算行数。即,您有一个月的所有金额的总和,但是该月的每一行都与上个月的所有行相连接。

使用几个子选择的解决方案:-

SELECT ThisMonth.MONTH, ThisMonth.YEAR, ThisMonth.TOTAL, PrevMonth.MONTH AS PREVIOUS_MONTH, PrevMonth.YEAR AS PREVIOUS_YEAR, PrevMonth.TOTAL AS PREVIOUS_TOTAL
FROM
(
    SELECT MONTH(start_date) AS `month`,
            YEAR(start_date) AS `year`,
            EXTRACT(YEAR_MONTH FROM start_date) AS YearMonth,
            SUM(amount) AS total
    FROM trackings
    GROUP BY `month`, `year`, YearMonth
) ThisMonth
LEFT OUTER JOIN
(
    SELECT MONTH(start_date) AS `month`,
            YEAR(start_date) AS `year`,
            EXTRACT(YEAR_MONTH FROM DATE_ADD(start_date, INTERVAL 1 MONTH)) AS YearMonth,
            SUM(amount) AS total
    FROM trackings
    GROUP BY `month`, `year`, YearMonth
) PrevMonth
ON ThisMonth.YearMonth = PrevMonth.YearMonth
于 2013-10-16T09:51:20.507 回答