【场景】:连续记录
【分类】:分组条件查询、窗口函数
分析思路
难点:
1.如何表示连接?连续的表示: 日期减去排序的值相等
2.记得先对日期、用户去重
(1)对用户、日期进行去重
- [使用]:distinct
(2)统计日期、用户、日期减去排序的值(连续签到)
连续的表示: 日期减去排序的值相等;
- [使用]:sales_date - row_number()
(3)统计连续2天及以上购物的用户及连续天数
-
[条件]:连续天数大于等于2天
-
[使用]:group by 分组条件 [用户] having count(连续天数) >= 2 order by [用户]
最终结果
select 查询结果 [创作者;等级;连续回答天数]
from 从哪张表中查询数据[多表]
group by 分组条件 [创作者;等级]
having 判断条件 [连续回答问题的天数大于等于3]
order by 对查询结果排序 [创作者升序];
扩展
前往查看: MySQL 连续记录 场景分析
求解代码
方法一:
with子句
with
main as(
#对用户、日期进行去重
select distinct
sales_date,
user_id
from sales_tb
)
,main1 as(
#统计日期、用户、日期减去排序的值(连续签到)
select distinct
sales_date,
user_id,
sales_date - row_number() over(partition by user_id order by sales_date) as date_i
from main
)
#连续2天及以上购物的用户及连续天数
select distinct
user_id,
count(date_i) as days_count
from main1
group by user_id having count(date_i) >= 2
方法二
多表嵌套
#连续2天及以上购物的用户及连续天数
select distinct
user_id,
count(date_i) as days_count
from(
#统计日期、用户、日期减去排序的值(连续签到)
select distinct
sales_date,
user_id,
sales_date - row_number() over(partition by user_id order by sales_date) as date_i
from(
#对用户、日期进行去重
select distinct
sales_date,
user_id
from sales_tb
) main
) main1
group by user_id having count(date_i) >= 2