mysql - 计算间隔之间的行数

标签 mysql

我的 table 是这样的:

+---------+---------+------------+-----------------------+---------------------+
| visitId | userId  | locationId | comments              | time                |
+---------+---------+------------+-----------------------+---------------------+
|       1 |    3    |     12     | It's a good day here! | 2012-12-12 11:50:12 |
+---------+---------+------------+-----------------------+---------------------+
|       2 |    3    |     23     | very beautiful        | 2012-12-12 12:50:12 |
+---------+---------+------------+-----------------------+---------------------+
|       3 |    3    |     52     | nice                  | 2012-12-12 13:50:12 |
+---------+---------+------------+-----------------------+---------------------+

记录访问者的轨迹以及对所访问地点的一些评论

我想统计在一定时间间隔(即 30 分钟)内从 0:00 到 23:59 访问特定地点(例如 id=3227)的访客数量

我试图通过以下方式做到这一点:

SELECT COUNT(*) FROM visits 
GROUP BY HOUR(time), SIGN( MINUTE(time) - 30 )// if they are in the same interval this will yield the same result
WHERE locationId=3227

问题是如果没有记录落在某个时间间隔内,则不会返回计数为 0 的该时间间隔。例如,从 02:00 到 02:00 没有访客访问该位置03:00,这不会给我 02:00-02:29 和 02:30-2:59 的间隔。

我想要一个精确大小为 48 的结果(每半小时一个),我该怎么做?

最佳答案

您必须创建一个包含所需 48 行的表并使用左外连接:

select n.hr, n.hr, coalesce(v.cnt, 0) as cnt
from (select 0 as hr, -1 as sign union all
      select 0, 1 union all
      select 1, -1 union all
      select 1, 1 union all
      . . .
      select 23, -1 union all
      select 23, 1 union all
     ) left outer join
     (SELECT HOUR(time) as hr, SIGN( MINUTE(time) - 30 ) as sign, COUNT(*) as cnt
      FROM visits 
      WHERE locationId=3227
      GROUP BY HOUR(time), SIGN( MINUTE(time) - 30 )
     ) v
     on n.hr = v.hr and n.sign = v.sign
order by n.hr, n.hr

关于mysql - 计算间隔之间的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15650423/

相关文章:

mysql - 如何在mysql中显示分组依据?

mysql - SQL 按姓氏对具有重复元组的表进行分组

java - JDBC/Java 应用程序端口扫描?

mysql - 由 : io. debezium.text.ParsingException 引起:外部输入 'ASC' 期望

mysql - R或Mysql : Change values of a column to null if they are not present in another row of the same dataframe

mysql - 此查询显示 #1248 - 每个派生表必须有自己的别名

mysql - SQL : Replace integer with string when there is empty value

php - session 变量的替代品?

php - MySQL 日期比较返回不同的结果

MySQL 按数字排序,最后为空