与上个月相比,MySQL月月总数

时间:2013-10-16 04:16:31

标签: mysql

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

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

1 个答案:

答案 0 :(得分: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