SQL每日一题03:查找连续出现问题

142 阅读1分钟

题目

编写一个 SQL 查询,查找所有至少连续出现两次的数字。

例如,给定上面的 T20191104表, 1 和2是连续出现至少两次的数字。

参考答案

create table T20191104
(
ID int,
Num int
);

insert into T20191104 values (1,1);
insert into T20191104 values (2,1);
insert into T20191104 values (3,1);
insert into T20191104 values (4,2);
insert into T20191104 values (5,1);
insert into T20191104 values (6,2);
insert into T20191104 values (7,2);

--MySQL 8.0和SQL Server

select t.Num,count(*) Times
FROM T20191104 t
where exists (
select 1 from T20191104 a
where a.Num=t.Num
and (a.ID=t.ID+1 OR a.ID=t.ID-1)
)
group by t.Num

答案解析

1、 这个解法是连续性题目的其中一种解法,主要是通过关联子查询和自连接来比较每一行的上下两行是否相等。

2、 如果相等就表示连续的,如果不相等就不连续,其中的where条件属于连续性判定中一种固定写法:

(a.ID=t.ID+1 OR a.ID=t.ID-1) -- 判定上下两行是否相等