MySQL聚合数据10天

时间:2014-11-11 12:25:07

标签: mysql aggregation

在MySQL中,我们说我需要每10天聚合一次。一段时间内的数据,例如

SELECT SUM(imps) FROM impressions i WHERE i.date BETWEEN SUBDATE('2014-11-10', 9) AND '2014-11-10'
UNION ALL 
SELECT SUM(imps) FROM impressions i WHERE i.date BETWEEN SUBDATE('2014-11-08', 9) AND '2014-11-08'
UNION ALL
SELECT SUM(imps) FROM impressions i WHERE i.date BETWEEN SUBDATE('2014-11-07', 9) AND '2014-11-07'
....
;

想象一下,我需要这样做一个月甚至更长时间,会有很多UNION ALL

我知道这可以通过在存储过程中使用循环来实现,但有没有办法在不使用存储过程的情况下执行此操作? I.e can GROUP BY子句可以解决这个问题吗?

谢谢!

表格展示的示例数据:     日期Imps     2014-11-10 10     2014-11-09 15     2014-11-08 7     ...

1 个答案:

答案 0 :(得分:1)

您可以将结果放在列中并使用条件聚合:

SELECT SUM(case when i.date BETWEEN SUBDATE('2014-11-10', 9) AND '2014-11-10' then imps else 0 end),
       SUM(case when i.date BETWEEN SUBDATE('2014-11-08', 9) AND '2014-11-08' then imps else 0 end),
       SUM(case when i.date BETWEEN SUBDATE('2014-11-07', 9) AND '2014-11-07' then imps else 0 end)    
FROM impressions i;

如果您希望它们位于不同的行中,那么您可以使用join,但需要一个值表:

SELECT SUM(case when i.date BETWEEN SUBDATE('2014-11-10', 9 + n.n) AND '2014-11-10' - interval n.n day
                then imps else 0 end)
FROM impressions i CROSS JOIN
     (SELECT 0 as n UNION ALL
      SELECT 1 UNION ALL
      SELECT 2
     ) n