sql求解连续两个以上的空座位

Q:查找电影院所有连续可用的座位。

返回按 seat_id 升序排序 的结果表。

测试用例的生成使得两个以上的座位连续可用。

结果表格式如下所示。

A:我们首先找出所有的空座位:1,3,4,5

按照seat_id排序(上面已经有序),并赋予排名,

seat_id rnk seta_id-rnk
1 1 0
3 2 1
4 3 1
5 4 1

我们发现连续的数与其对应的排名均是连续的,那么两者相减应该等于相同的数,因此可以分为以下几步

sql 复制代码
# 1. t1:获取所有空座位
select seat_id from Cinema where free=1

# 2. t2:获取所有的连续数字对应的组
select
seat_id,
seat_id-row_number() over(order by seat_id) diff
from
(
	select seat_id from Cinema where free=1
) t1

# 3. t3:连续的数对应的diff是相同的,可以按照diff分组,并收集空座位号大于等于2的组号
select
diff
from 
(
	select
	seat_id,
	seat_id-row_number() over(order by seat_id) diff
	from
		(
			select seat_id from Cinema where free=1
		) t1
) t2
group by diff having count(seat_id) >=2

# 4. 根据t2表以及t3表获取大于等于2个以上的空座位号
select 
seat_id
from 
(
	select
	seat_id,
	seat_id-row_number() over(order by seat_id) diff
	from
	(
		select seat_id from Cinema where free=1
	) t1
) t2
where diff in 
(
	select
	diff
	from 
	(
		select
		seat_id,
		seat_id-row_number() over(order by seat_id) diff
		from
			(
				select seat_id from Cinema where free=1
			) t1
	) t2
	group by diff having count(seat_id) >=2
) 

因此,最终代码为:

sql 复制代码
select 
seat_id
from 
(
	select
	seat_id,
	seat_id-row_number() over(order by seat_id) diff
	from
	(
		select seat_id from Cinema where free=1
	) t1
) t2
where diff in 
(
	select
	diff
	from 
	(
		select
		seat_id,
		seat_id-row_number() over(order by seat_id) diff
		from
			(
				select seat_id from Cinema where free=1
			) t1
	) t2
	group by diff having count(seat_id) >=2
) 
相关推荐
元气满满-樱38 分钟前
SQL语句***重点
数据库·sql
小白勇闯网安圈3 小时前
unserialize3、php_rce、Web_php_include、warmup、NewsCenter
sql·网络安全·web
思成不止于此4 小时前
【MySQL 零基础入门】DCL 核心语法全解析:用户管理与权限控制篇
数据库·笔记·sql·学习·mysql
weixin_447671995 小时前
【MySQL从节点异常断连后的Slave_SQL_Running 处于Connecting的解决方案】
android·sql·mysql
roman_日积跬步-终至千里5 小时前
【源码分析】StarRocks TRUNCATE 语句执行流程:从 SQL 到数据清空的完整旅程
java·数据库·sql
ClouGence5 小时前
从 0 到 1 构建 TDSQL MySQL 实时同步链路
数据库·分布式·sql·mysql
Hello.Reader5 小时前
Flink SQL 的 LIMIT 子句语义、坑点与实战技巧
sql·flink·wpf
Hello.Reader5 小时前
Flink SQL 集合运算UNION / INTERSECT / EXCEPT 以及 IN / EXISTS 在流式场景下怎么用?
数据库·sql·flink
Arva .6 小时前
详细描述一条 SQL 在 MySQL 中的执行过程
数据库·sql·mysql
亚林瓜子6 小时前
在AWS Athena中使用json_extract_scalar函数对某个json字段进行过滤和分组统计
sql·json·aws·athena