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
) 
相关推荐
木木子99996 小时前
SQL138 连续两次作答试卷的最大时间窗
sql·题解记录
抛砖者6 小时前
hive/spark sql中unix_timestamp 函数的坑以及时间戳相关的转换
hive·sql·spark
野犬寒鸦13 小时前
MyBatis-Plus 中使用 Wrapper 自定义 SQL
java·数据库·后端·sql·mybatis
~ 小团子15 小时前
每日一SQL 【游戏玩法分析 IV】
数据库·sql·游戏
尽兴-1 天前
如何将多个.sql文件合并成一个:Windows和Linux/Mac详细指南
linux·数据库·windows·sql·macos
IvanCodes1 天前
Oracle 视图
大数据·数据库·sql·oracle
渣渣盟2 天前
掌握MySQL函数:高效数据处理指南
sql·mysql·adb·dba
??? Meggie2 天前
【SQL】使用UPDATE修改表字段的时候,遇到1054 或者1064的问题怎么办?
android·数据库·sql
工藤学编程2 天前
分库分表之实战-sharding-JDBC绑定表配置实战
数据库·分布式·后端·sql·mysql
在安全厂商修设备2 天前
SQL注入与防御-第六章-3:利用操作系统--巩固访问
sql·web安全·网络安全