Mysql:如何每周检索数据

时间:2016-03-07 10:11:30

标签: mysql

我有这样的数据:

enter image description here

现在我想像每周一样打印这些数据

+------------+-----------+
|    weeks   | sum(count)| 
+----------- +-----------+
| week 1     |  2526     | 
| week 2     |  26987    |
+------------+-----------+

这个查询总和所有mimi_count但我想要的数字可能是上面的数字格式

  

分组

。我搜索了很多但找不到我想要的东西

SELECT sum(mimie_count) as mimie 
FROM statistics 
WHERE mimiDate >    DATE_SUB(NOW(), INTERVAL 1 WEEK)

1 个答案:

答案 0 :(得分:2)

SELECT 
WEEK(mimiDate) weeks,
sum(mimie_count) as mimie 
FROM statistics 
WHERE mimiDate >    DATE_SUB(NOW(), INTERVAL 5 WEEK)
GROUP BY WEEK(mimiDate)
ORDER BY mimiDate;

注意:如果您希望每周最后X周总和,请使用此DATE_SUB(NOW(), INTERVAL X WEEK)。另请注意,WEEK函数假定一周的开头为Monday

修改 如果您想要像您所说的第一列,那么您需要采用以下查询:

SELECT 
    CONCAT('week ',WEEK(mimiDate)) weeks,
    sum(mimie_count) as mimie 
    FROM statistics 
    WHERE mimiDate >    DATE_SUB(NOW(), INTERVAL 5 WEEK)
    GROUP BY WEEK(mimiDate)
    ORDER BY mimiDate;

对于特定日期范围搜索:

SELECT 
    CONCAT('week ',WEEK(mimiDate)) weeks,
    sum(mimie_count) as mimie 
    FROM statistics 
    WHERE mimiDate BETWEEN '2016-01-21' AND ' 2016-03-05'
    GROUP BY WEEK(mimiDate)
    ORDER BY mimiDate;