按月分组,汇总值和滚动年份

时间:2018-10-31 10:29:29

标签: mysql date group-by

我正在尝试在MySQL中按月对销售数据进行分组,但是具有滚动的年度总和值。 预期输出示例:

Month                           SUM
January 2018    Total from february 2017 to january 2018 (12months)
February 2018   Total from march 2017 to february 2018 (12months)
...

这是我到目前为止得到的:

SELECT YEAR(date), MONTH(date), 
(SELECT SUM(quantity) FROM tb t2 WHERE t2.date BETWEEN DATE_SUB(t1.date, INTERVAL 1 YEAR) AND t1.date)
FROM tb t1
WHERE date BETWEEN '2018-01-01' AND '2019-01-01'
GROUP BY YEAR(date), MONTH(date)

结果是预期的,但是效率很低,因为如果我使用3天的间隔,则需要30秒才能运行(所以我什至不能以1年的间隔运行)

任何想法如何改进此查询,以便我可以使用1年间隔?在特定字段上是否需要索引?

修改: 创建语句:

CREATE TABLE IF NOT EXISTS `tb` (
  `inc` int(11) NOT NULL AUTO_INCREMENT,
  `quantity` float NOT NULL,
  `date` datetime NOT NULL,
  PRIMARY KEY (`inc`),
  KEY `date` (`date`)
) ENGINE=InnoDB;

它有超过10万行,我无法升级到MySQL> = 8

1 个答案:

答案 0 :(得分:0)

代替使用子查询,“内部自连接”可以更有效。请尝试以下操作:

SELECT 
  YEAR(t1.date), 
  MONTH(t1.date), 
  SUM(t2.quantity) 
FROM tb AS t1 
JOIN tb AS t2 
  ON t2.date BETWEEN (t1.date - INTERVAL 1 YEAR) AND t1.date 
WHERE t1.date BETWEEN '2018-01-01' AND '2019-01-01'
GROUP BY YEAR(t1.date), MONTH(t1.date)