编写一个SQL实现查找所有至少连续三次出现的数字的三种方法
题干
已知t1.txt存储了以下数据
20230801,1
20230802,1
20230803,1
20230804,2
20230805,1
20230806,2
20230807,2
20230808,3
20230809,3
20230810,3
20230811,3
20230812,4
需求
编写一个SQL实现查找所有至少连续三次出现的数字
答案
create table if not exists t1(
id string,
number int
)
row format delimited
fields terminated by ",";
load data inpath "/input/d1.txt" into table t1;
select * from t1;
with tmp1 as (
select id,number,
max(number) over(partition by null order by id rows between 1 preceding and 1 following) as max_num,
min(number) over(partition by null order by id rows between 1 preceding and 1 following) as min_num
from t1
)
select distinct number
from tmp1
where max_num = min_num;
with tmp2 as (
select id,
number,
lag(number) over(partition by null order by id ) as f1_num
from t1
),
tmp3 as (
select id,
number,
f1_num,
lag(f1_num) over(partition by null order by id ) as f2_num
from tmp2
)
select distinct number
from tmp3
where number = f1_num and number = f2_num;
select distinct (a.number) from test_data4 a, test_data4 b, test_data4 c
where a.id = b.id - 1 and b.id = c.id - 1
and a.number=b.number and b.number = c.number;
select distinct(a.number) as continuenum from test_data4 a
join test_data4 b on a.id = b.id - 1
join test_data4 c on b.id = c.id - 1