是否可以根据日期分组来汇总列的结果?

时间:2014-06-20 15:23:34

标签: mysql sql datetime

这里有一个示例表:

 id |    datetime         | views
 --------------------------------
 1  | 2014-02-27 21:00:00 | 200
 65 | 2014-02-08 05:00:00 | 1
 65 | 2014-02-08 10:00:00 | 3
 65 | 2014-02-08 17:00:00 | 1
 65 | 2014-02-08 20:00:00 | 1
 65 | 2014-02-08 21:00:00 | 1
 65 | 2014-02-09 04:00:00 | 2
 65 | 2014-02-09 05:00:00 | 1
 65 | 2014-02-09 06:00:00 | 3
 65 | 2014-02-09 07:00:00 | 1
 65 | 2014-02-09 09:00:00 | 1
 65 | 2014-02-09 10:00:00 | 2
 65 | 2014-02-09 13:00:00 | 1
 70 | 2014-02-09 14:00:00 | 3
 70 | 2014-02-09 15:00:00 | 2

我试图获取每天特定id的视图而不是每小时(这是此表的设置)。最好的方法是什么?

3 个答案:

答案 0 :(得分:2)

SELECT `id`
     , DATE(`datetime`)
     , SUM(`views`)
FROM `table`
GROUP BY `id`
        , DATE(`datetime`) 

答案 1 :(得分:2)

您可以使用DATE function获取日期时间值的日期部分:

SELECT
     id,
     DATE(datetime) AS mydate,
     SUM(views) AS total
FROM
     yourtable
GROUP BY
     id,
     DATE(datetime);

答案 2 :(得分:0)

SELECT sum(views) as vievs, DATE(datetime) as date
FROM table
GROUP BY DATE(datetime);