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
) 
相关推荐
Cachel wood9 小时前
后端开发:计算机网络、数据库常识
android·大数据·数据库·数据仓库·sql·计算机网络·mysql
Lx35211 小时前
SQL参数化查询:防注入与计划缓存的双重优势
后端·sql·mysql
BillKu12 小时前
sql中like and not like的优化
数据库·sql
夜光小兔纸19 小时前
SQL Server 查询数据库中所有表中所有字段的数据类型及长度
数据库·sql·sql server
唐人街都是苦瓜脸1 天前
学习Oracle------Oracle和mysql在SQL 语句上的的异同 (及Oracle在写SQL 语句时的注意事项)
sql·mysql·oracle
Edingbrugh.南空1 天前
Hive SQL执行流程深度解析:从CLI入口到执行计划生成
hive·hadoop·sql
Edingbrugh.南空1 天前
Hive SQL 执行计划详解:从查看方法到优化应用
hive·hadoop·sql
Edingbrugh.南空2 天前
Hive SQL:一小时快速入门指南
hive·hadoop·sql
vace cc2 天前
sql列中数据通过逗号分割的集合,对其中的值进行全表查重
数据库·sql
安替-AnTi2 天前
基于Django的购物系统
python·sql·django·毕设·购物系统