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
) 
相关推荐
好奇的菜鸟3 小时前
Spring Boot 事务失效问题:同一个 Service 类中方法调用导致事务失效的原因及解决方案
数据库·spring boot·sql
float_六七8 小时前
SQL六大核心类别全解析
数据库·sql·oracle
He.ZaoCha15 小时前
函数-1-字符串函数
数据库·sql·mysql
Code季风19 小时前
SQL关键字快速入门:HAVING 分组后的条件过滤
数据库·sql·mysql
星辰离彬1 天前
Java 与 MySQL 性能优化:Java应用中MySQL慢SQL诊断与优化实战
java·后端·sql·mysql·性能优化
zhuiQiuMX1 天前
脉脉maimai面试死亡日记
数据仓库·sql·面试
GEEK零零七2 天前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
御控工业物联网2 天前
御控网关如何实现MQTT、MODBUS、OPCUA、SQL、HTTP之间协议转换
数据库·sql·http
Code季风2 天前
SQL关键字快速入门:CASE 实现条件逻辑
javascript·数据库·sql
kk在加油2 天前
Mysql锁机制与优化实践以及MVCC底层原理剖析
数据库·sql·mysql