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
) 
相关推荐
2501_9336707910 小时前
内容电商运营岗位能力模型:SQL、Excel、投放数据与AI工具怎么准备
人工智能·sql·excel
子非鱼a11 小时前
【WEB】October 2019 Twice SQL Injection
数据库·sql
Elastic 中国社区官方博客11 小时前
Elasticsearch:ES|QL 搜索教程
大数据·数据库·人工智能·sql·elasticsearch·搜索引擎·全文检索
喂自己代言11 小时前
从 0.7 秒到 11 毫秒:OceanBase 一条慢 SQL 的三连坑优化实战
数据库·sql·oceanbase
鸽芷咕11 小时前
金仓KES向量数据库实战:一条SQL干掉ETL,机器人不再把停产货当现货卖
数据库·sql·etl
YHHLAI1 天前
SQL 完全指南:从入门到精通
数据库·sql
CDN3601 天前
爬虫把价格库扒光、SQL注入打穿数据库?360CDN WAF规则引擎深度定制,把防护精度拉到逐字段级
数据库·爬虫·sql
天涯柳絮1 天前
SQL注入
数据库·sql·网络安全
Ysx2 天前
把 SQL 从 2700 次降到 4 次:一个 Java 后端对存量报表的 N+1 手术
sql
2301_800074212 天前
mysql DQL
数据库·sql·mysql