题目
几个朋友来到电影院的售票处,准备预约连续空余座位。你能利用表 cinema ,帮他们写一个查询语句,获取所有空余座位,并将它们按照 seat_id 排序后返回吗?
对于如上样例,你的查询语句应该返回如下结果。
seat_id 字段是一个自增的整数,free 字段是布尔类型(’1’ 表示空余, ‘0’ 表示已被占据)。
连续空余座位的定义是大于等于 2 个连续空余的座位。
数据准备
create table cinema (
seat_id int,
free int
);
insert into cinema values(1,1);
insert into cinema values(2,0);
insert into cinema values(3,1);
insert into cinema values(4,1);
insert into cinema values(5,1);
insert into cinema values(6,0);
insert into cinema values(7,1);
insert into cinema values(8,1);
解题
本题考查和连续时间类似,先按照free分组,座位ID排序,计算排序与座位ID的差值
SELECT seat_id ,
free ,
ROW_NUMBER() OVER (PARTITION BY free ORDER BY seat_id) rn1,
ROW_NUMBER() OVER (PARTITION BY free ORDER BY seat_id) - seat_id diff
FROM dbo.cinema
WHERE free = 1 --之需要计算free = 1的未被占用座位
计算出连续的diff值
SELECT
T.free,
diff,
COUNT( 1 ) Times
FROM
(
SELECT
seat_id,
free,
ROW_NUMBER ( ) OVER ( PARTITION BY free ORDER BY seat_id ) rn1,
ROW_NUMBER ( ) OVER ( PARTITION BY free ORDER BY seat_id ) - seat_id diff
FROM
dbo.cinema
WHERE
free = 1
) T
GROUP BY
T.free,
diff
HAVING
COUNT( 1 ) > 1
再同diff关联查找出对应的座位ID
SELECT
seat_id
FROM
(
SELECT
T.free,
diff,
COUNT( 1 ) Times
FROM
(
SELECT
seat_id,
free,
ROW_NUMBER ( ) OVER ( PARTITION BY free ORDER BY seat_id ) rn1,
ROW_NUMBER ( ) OVER ( PARTITION BY free ORDER BY seat_id ) - seat_id diff
FROM
dbo.cinema
WHERE
free = 1
) T
GROUP BY
T.free,
diff
HAVING
COUNT( 1 ) > 1
) t
LEFT JOIN (
SELECT
seat_id,
free,
ROW_NUMBER ( ) OVER ( PARTITION BY free ORDER BY seat_id ) rn1,
ROW_NUMBER ( ) OVER ( PARTITION BY free ORDER BY seat_id ) - seat_id diff
FROM
dbo.cinema
WHERE
free = 1
) T2 ON t2.diff = t.diff;