1

这些年写过的花式sql - 第3句 今日流失用户

 1 year ago
source link: https://www.cnblogs.com/xjcyue/p/17605942.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

第3句 今日流失用户

当日流失用户的定义:昨天登录的,今天没登录的用户数
有一张用户登录日志表,有字段 date_stamp(日期时间戳),用户id(uid)。如果用户在某天登录了,该表会有一条记录。

#今天流失人数:昨天登录,今天没登录的
select a.date_stamp+86400  as date ,count(*) as num
from        
    user_date a
    left join user_date b
    on  a.date_stamp = b.date_stamp -86400 and a.uid =b.uid
where b.date_stamp is null and a.date_stamp+86400 >=UNIX_TIMESTAMP('2023-08-01 00:00:00')
group by date

a 表和b表的连接条件是 uid相同 且时间戳相差一天,a 即前一天,b即当天。 如果流失了,则 a 存在而b不存在。查出结果之后 因为要算当天,a的时间戳需要加一天。
同理可以写出类似的 复活用户数(前一天未登录,当天登录)和 留存用户数(前一天和当天都登录的用户数)
注意点: 我们经常会用到 select x as y 这样的语句,但是这个 y 只能用在 group 子句,而where 后面是不可以的。
知识点表的多重连接条件

ps: 这个查询速度比较慢,欢迎大佬们提出优化建议


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK