如何用SQL解决连续几天的问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何用SQL解决连续几天的问题相关的知识,希望对你有一定的参考价值。

参考技术A 统计下用户最长连续登录的天数”,“统计下连续登录超过10天的用户”,“统计下连续3天交易额超过100W的店铺

1. 连续两天购买的用户

先按照date将一天多次进行去重

row1:按照Date分组,time排序

row2:按照Date和ID分组,time排序

按照ID、row2-row1 分组,重复次数大于1

2. 比如连续2次购买的用户() 

row1:按照  time排序

row2:按照 ID 分组,time排序

按照ID、row2-row1 分组,重复次数大于1

2. 连续2次购买苹果的用户

row1:按照 time排序

row2:按照ID、商品类型分组,time排序

按照ID、商品类型分组,重复次数大于1

3. 连续2次在淘宝购买苹果的用户

row1:按照 time排序

row2:按照ID、商品类型、店铺分组,time排序

按照ID、商品类型、店铺分组,重复次数大于1

如何用sql查询出连续三个月金额大于50的记录

with tmp as
(
select ‘A‘ AS USERNAME,to_date(‘2017.10‘,‘yyyy.mm‘) month,45 num from dual union all
select ‘A‘ AS USERNAME,to_date(‘2017.11‘,‘yyyy.mm‘) month,53 from dual union all
select ‘A‘ AS USERNAME,to_date(‘2017.12‘,‘yyyy.mm‘) month,59 from dual union all
select ‘B‘ AS USERNAME,to_date(‘2018.1‘,‘yyyy.mm‘) month,78 from dual union all
select ‘B‘ AS USERNAME,to_date(‘2018.2‘,‘yyyy.mm‘) month,69 from dual union all
select ‘B‘ AS USERNAME,to_date(‘2018.3‘,‘yyyy.mm‘) month,51 from dual union ALL
select ‘B‘ AS USERNAME,to_date(‘2018.5‘,‘yyyy.mm‘) month,49 from dual union ALL
select ‘B‘ AS USERNAME,to_date(‘2018.4‘,‘yyyy.mm‘) month,51 from dual union ALL
select ‘B‘ AS USERNAME,to_date(‘2018.6‘,‘yyyy.mm‘) month,49 from dual union ALL
select ‘A‘ AS USERNAME,to_date(‘2017.9‘,‘yyyy.mm‘) month,52 from dual union ALL
select ‘A‘ AS USERNAME,to_date(‘2017.7‘,‘yyyy.mm‘) month,49 from dual union ALL
select ‘A‘ AS USERNAME,to_date(‘2017.8‘,‘yyyy.mm‘) month,55 from dual
)
select USERNAME,month start_month,num,num2,num3 from
( select USERNAME,
month,
num,
lead(num, 1, null) over(PARTITION BY username order by month) num2,
lead(num, 2, null) over(PARTITION BY username order by month) num3
from tmp order by username,month)
--where num >=50 and num2 >=50 and num3 >=50

以上是关于如何用SQL解决连续几天的问题的主要内容,如果未能解决你的问题,请参考以下文章

如何用整数列做 group_concat?

sql 语句:一个字段,连续几天值大于0,获得天数 怎么解决的?请教

sql 语句:一个字段,连续几天值大于0,获得天数 怎么解决的?请教

郁闷了几天的问题终于解决了

如何用sql查询出连续三个月金额大于50的记录

如何用python计算某支股票持有90天的收益率