- 学习:知识的初次邂逅
- 复习:知识的温故知新
- 练习:知识的实践应用
目录
一,原题力扣链接
二,题干
表:
Cinema
+-------------+------+ | Column Name | Type | +-------------+------+ | seat_id | int | | free | bool | +-------------+------+ Seat_id 是该表的自动递增主键列。 在 PostgreSQL 中,free
存储为整数。请使用::boolean
将其转换为布尔格式。 该表的每一行表示第 i 个座位是否空闲。1 表示空闲,0 表示被占用。查找电影院所有连续可用的座位。
返回按
seat_id
升序排序 的结果表。测试用例的生成使得两个以上的座位连续可用。
结果表格式如下所示。
示例 1:
输入: Cinema 表: +---------+------+ | seat_id | free | +---------+------+ | 1 | 1 | | 2 | 0 | | 3 | 1 | | 4 | 1 | | 5 | 1 | +---------+------+ 输出: +---------+ | seat_id | +---------+ | 3 | | 4 | | 5 | +---------+
三,建表语句
Create table If Not Exists Cinema (seat_id int primary key auto_increment, free bool);
Truncate table Cinema;
insert into Cinema (seat_id, free) values ('1', '1');
insert into Cinema (seat_id, free) values ('2', '0');
insert into Cinema (seat_id, free) values ('3', '1');
insert into Cinema (seat_id, free) values ('4', '1');
insert into Cinema (seat_id, free) values ('5', '1');
select * from Cinema;
四,分析
表格分析:
解答思路:
题解
表:电影院表
字段:座位id,空闲与否
题目要求,连续的空闲的座位
遇到连续的问题,首选给其做一个排名,然后减去差值,若差值一样则为连续;
第一步:去除非空闲
第二步: 用id-rn 做一个排名 如果相同则表示连续
第三步:开窗求次数 题目要求至少连续2次的;
最后一步,根据pm2求seat_id 然后做一个排序
五,SQL解答
with t1 as (
select *,
row_number() over () rn
from cinema where free =1
),t2 as (
select *,
seat_id-rn as pm
from t1
),t3 as (
select *,
count(seat_id) over (partition by pm) pm2
from t2
),t4 as (
select seat_id from t3 where pm2>=2 order by seat_id
)
select * from t4;
六,验证
七,知识点总结
- 连续问题,首选用排名和差值计算
- 开窗函数的运用
- 排序的运用
- 学习:知识的初次邂逅
- 复习:知识的温故知新
- 练习:知识的实践应用