2016-07-14 90 views
3

我有一个名为Theater(Sn, SeatVacant)具有相同的列值的3倍以上选择行

e.g SN SEATVACANT 
    1 Y 
    2 Y 
    3 N 
    . . 
    . . 
    100 Y 

我要预订3个席位(应该是连续的)表。我怎样才能获得连续空缺的座位。

+5

*差距和离岛* - 例如[从表中查找“n”个连续的免费号码)(http://dba.stackexchange.com/questions/36943/find-n-consecutive-free-numbers-from-table) –

+1

如果这确实代表了剧院,那么我怀疑有一排100个座位。所以你可能还需要考虑哪些座位在数字上是连续的,但不是彼此相邻。 – sstan

回答

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' 
+0

谢谢。它的工作....但它是一个静态的解决方案,我可以做到动态。例如x个连续空置的座位 –

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 
1

这样,如果你想要一个动态的解决方案:

--Theater(Sn, SeatVacant) 

DECLARE @ContiguougsSeats AS INT 
SET @ContiguougsSeats = 4 

SELECT Sn, ' to ', [email protected] 
FROM Theater As t1 
WHERE [email protected] <= (Select MAX(Sn) From Theater) 
    AND NOT EXISTS(
    Select * 
    From Theater As t2 
    Where t2.Sn Between t1.Sn AND [email protected] 
     And t2.SeatVacant = 'N' 
    ) 
+1

不错,当你录制你的代码时有点错误,t2.SEATVACANT ='N' – Esperento57

+1

@ Esperento57谢谢,现在修复。 – RBarryYoung

相关问题