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
) 
相关推荐
祖传F8712 小时前
quickbi数据集数据查询时间字段显示正确,仪表板不显示
数据库·sql·阿里云
悟道子HD13 小时前
SRC漏洞挖掘——2.SQL注入漏洞实战详解
sql·web安全·网络安全·渗透测试·sql注入·sqlmap·暴力破解
需要点灵感15 小时前
SQL Server 存储过程语法整理
数据库·sql
沃尔威武16 小时前
性能调优实战:从火焰图定位到SQL优化的全流程
android·数据库·sql
数厘16 小时前
2.7SQL 四大分类:理解与避坑
数据库·sql
XDHCOM17 小时前
ORA-31215: DBMS_LDAP PL/SQL无效LDAP修改值,Oracle报错故障修复与远程处理方案,快速解决连接配置难题
数据库·sql·oracle
rockey62717 小时前
AScript动态脚本多语言环境支持
sql·c#·.net·script·eval·function·动态脚本
逆境不可逃19 小时前
高频 SQL 50 题 之 连接篇 1378 1068 1581 197 1661 577 1280 570 1934
数据库·sql
A__tao21 小时前
一键实现 SQL 转 Elasticsearch Mapping(支持字段注释 + meta 描述)
数据库·sql·elasticsearch
Dreamboat¿1 天前
SQL 注入漏洞
数据库·sql