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
) 
相关推荐
做运维的阿瑞8 小时前
数据库增删改的安全写法
数据库·sql·mysql
小马哥程序开发10 小时前
[点赞收藏免费领取 · 项目源码]37399民族服饰饰品商城小程序
sql·mysql·flask·源码·课程设计·程序开发·课设
煎饼皮皮侠14 小时前
设计一个Web版数据库管理平台(之六):SQL执行监听器 —— 日志、监控与审计
sql·数据库平台
bksczm16 小时前
MySQL进阶篇之范式及E-R图
数据库·sql·mysql
步行cgn16 小时前
Spring 负责注入的注解详解
java·sql·spring
码农-0041 天前
Springboot 集成 Ehcache操作数据库显示SQL语句设置
数据库·spring boot·sql
钱栈up1 天前
全量 21 个失败、单跑全绿:泄漏进连接池的 SQL 变量
sql·单元测试·测试
旺仔不是程序员1 天前
pg_trgm GIN 索引:PostgreSQL 正则、模糊与近似度查询的三合一加速器
数据库·后端·sql
考虑考虑1 天前
SQL中的 CASE WHEN
数据库·后端·sql
旺仔不是程序员1 天前
索引膨胀与重建:PostgreSQL REINDEX 生产实践
数据库·后端·sql