MySQL 查询连续出现多次数据

Q:

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

Demo_table:

Id Num
1 1
2 1
3 1
4 2
5 1
6 2
7 2

A:

select distinct 
	l1.Num as ConsecutiveNums
from 
	Demo_table l1,
	Demo_table l2,
	Demo_table l3
where 
	l1.Id = l2.Id - 1
	And l2.Id = l3.Id -1
	And l1.Num = l2.Num
	And l2.Num = l3,Num
	;

释:

  • 通过连续的 Id -1 可确保他们的连续性
  • 然后一一比对相等

猜你喜欢

转载自blog.csdn.net/weixin_44355591/article/details/105955433