我有一张名为Theater(Sn, SeatVacant)
e.g SN SEATVACANT
1 Y
2 Y
3 N
. .
. .
100 Y
我想预订3个座位(应该是连续的)。我怎样才能获得连续空缺的座位。
答案 0 :(得分:1)
select f1.sn, f2.sn, f3.sn from Theater f1
inner join Theater f2 on f1.sn=f2.sn + 1
inner join Theater f3 on f1.sn=f3.sn + 2
where f1.SEATVACANT='Y' and f2.SEATVACANT='Y' and f3.SEATVACANT='Y'
答案 1 :(得分:1)
with tablenewkey as(
select ROW_NUMBER() over(order by f1.sn) newkey, f1.* from theater f1
),
nbplacevacant as (
select 3 as NbrowByGroup
),
calculdiff as (
select f1.*, isnull(f3.newkey, 0) newkeylastN, f1.newkey - isnull(f3.newkey, 0) DiffYWithLasN
from tablenewkey f1
outer apply
(
select top 1 * from tablenewkey f2
where f2.newkey<f1.newkey and f2.SEATVACANT='N'
order by f2.newkey desc
) f3
where f1.SEATVACANT='Y' and (f1.newkey - isnull(f3.newkey, 0))>=(select NbrowByGroup from nbplacevacant)
),
possibilite as (
select f0.*, f1.newkey Groupement, f1.DiffYWithLasN
from tablenewkey f0 inner join calculdiff f1
on f0.newkey between (f1.newkey - DiffYWithLasN +1) and f1.newkey
where f0.SEATVACANT='Y'
)
select newkey, sn, Groupement, DENSE_RANK() over(order by Groupement) PossiblilityRang from possibilite
order by groupement, sn
答案 2 :(得分:1)
像这样,如果你想要一个动态的解决方案:
--Theater(Sn, SeatVacant)
DECLARE @ContiguougsSeats AS INT
SET @ContiguougsSeats = 4
SELECT Sn, ' to ', Sn+@ContiguougsSeats-1
FROM Theater As t1
WHERE t1.Sn+@ContiguougsSeats-1 <= (Select MAX(Sn) From Theater)
AND NOT EXISTS(
Select *
From Theater As t2
Where t2.Sn Between t1.Sn AND t1.Sn+@ContiguougsSeats-1
And t2.SeatVacant = 'N'
)