现有一表user_login_table代表表名
user_name代表用户ID
date代表用户登录时间
其结构数据如下:

例题4.将一天划分为24小时,先需统计用户在不同时间段内的登录情况
#假设一个用户在同一天的同一时间登录仅记录一次,换句话说,就是统计同一天的同一时间段登录未去重用户数
思路:通过hour函数得到小时数,通过小时数group by 在count
具体代码如下:
select hour(date) as hour1,
count(user_name)
from user_login_table
group by hour1;
#假设一个用户可能在一段时间内重复登录,统计同一天同一时间去重之后的用户登录数据
思路:截取date 的日期、时间-用concat函数将日期和时间合并为concat_hour,通过group by concat_hour 统计去重的用户-然后通过substring_index函数截取时间-通过时间分组求和得到不同时间短内的去重用户登录数据
具体代码如下:
select sub,
sum(count1)
from (select substring_index(concat_hour,"-",-1) as sub,
count1
from(select concat(date,"-",hour) as concat_hour,
count(distinct user_name) as count1
from (select user_name,
date(date) as date,
hour(date) as hour
from user_login_table)a
group by concat_hour)b) c
group by sub;
补充知识点:
连接字符串
concat(str1,str2,...)-多个字符串连接为1个字符串
concat_ws(分隔符,str1,str2,...)-多个字符串连接为1个字符串,一次性制定分隔符
group_concat()-将group by产生的同一个分组中的值连接起来,返回一个字符串结果
具体内容可参考以下文章:
https://blog.csdn.net/mary19920410/article/details/76545053/
截取字符串
从左边截取-left
从右边截取- right
按指定分隔符截取指定位置的字符-substring_index(str1,分隔符,截取字符串位置)
2个时间之差-subtime(expr1,expr2)
具体内容可参考以下文章:
https://blog.csdn.net/qq_37512323/article/details/86507041




