分组X天

时间:2011-01-20 18:31:52

标签: mysql group-by grouping

我有一组或多个记录,我想计算并按特定范围对它们进行分组,例如我想计算由X天组创建的记录

e.g. SELECT COUNT(*) FROM `table` GROUP BY /*`created` 3 days/*

3 个答案:

答案 0 :(得分:6)

以下是日期示例。

create table t1(created date not null);

insert 
  into t1(created) values (date '2011-01-09')
                         ,(date '2011-01-10')
                         ,(date '2011-01-11')
                         ,(date '2011-01-12')
                         ,(date '2011-01-13')
                         ,(date '2011-01-14')
                         ,(date '2011-01-15')
                         ,(date '2011-01-16')
                         ,(date '2011-01-17')
                         ,(date '2011-01-18')
                         ,(date '2011-01-19')
                         ,(date '2011-01-20');

select floor(datediff(now(), created) / 3) * 3 as days_ago
      ,min(created)
      ,max(created)
      ,count(*)
  from t1
 group 
    by floor(datediff(now(), created) / 3);

+----------+--------------+--------------+----------+
| days_ago | min(created) | max(created) | count(*) |
+----------+--------------+--------------+----------+
|        0 | 2011-01-18   | 2011-01-20   |        3 |
|        3 | 2011-01-15   | 2011-01-17   |        3 |
|        6 | 2011-01-12   | 2011-01-14   |        3 |
|        9 | 2011-01-09   | 2011-01-11   |        3 |
+----------+--------------+--------------+----------+
4 rows in set (0.00 sec)

答案 1 :(得分:3)

你可以做类似的事情 SELECT COUNT(*) FROM table GROUP BY FLOOR(created / 3)

......我想。

虽然如果created是一个日期字段,您必须做一些更多的跳汰才能将其设置为数字值才能使其生效。

答案 2 :(得分:1)

谢谢@Ronnis,我用你的例子,最后解决了我的问题。

我发现了一个小错误,例如,我添加了一行

insert into t1(created) values (date '2011-01-21')

现在我明白了:

+----------+--------------+--------------+----------+
| days_ago | min(created) | max(created) | count(*) |
+----------+--------------+--------------+----------+
|     1986 | 2011-01-20   | 2011-01-21   |        2 |
|     1989 | 2011-01-17   | 2011-01-19   |        3 |
|     1992 | 2011-01-14   | 2011-01-16   |        3 |
|     1995 | 2011-01-11   | 2011-01-13   |        3 |
|     1998 | 2011-01-09   | 2011-01-10   |        2 |
+----------+--------------+--------------+----------+

正如你所看到的那样,天数分为2,3,3,3,2,这不是我的预期。

我将SQL更改为

select floor(datediff(created, '2011-01-09') / 3) * 3 as days_before
      ,min(created)
      ,max(created)
      ,count(*)
from t1
group by floor(datediff(created, '2011-01-09') / 3);

从创建到开始日期获取日期,现在我得到:

+-------------+--------------+--------------+----------+
| days_before | min(created) | max(created) | count(*) |
+-------------+--------------+--------------+----------+
|           0 | 2011-01-09   | 2011-01-11   |        3 |
|           3 | 2011-01-12   | 2011-01-14   |        3 |
|           6 | 2011-01-15   | 2011-01-17   |        3 |
|           9 | 2011-01-18   | 2011-01-20   |        3 |
|          12 | 2011-01-21   | 2011-01-21   |        1 |
+-------------+--------------+--------------+----------+

这可能更适合。