我有一個名爲Theater(Sn, SeatVacant)
具有相同的列值的3倍以上選擇行
e.g SN SEATVACANT
1 Y
2 Y
3 N
. .
. .
100 Y
我要預訂3個席位(應該是連續的)表。我怎樣才能獲得連續空缺的座位。
我有一個名爲Theater(Sn, SeatVacant)
具有相同的列值的3倍以上選擇行
e.g SN SEATVACANT
1 Y
2 Y
3 N
. .
. .
100 Y
我要預訂3個席位(應該是連續的)表。我怎樣才能獲得連續空缺的座位。
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'
謝謝。它的工作....但它是一個靜態的解決方案,我可以做到動態。例如x個連續空置的座位 –
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
這樣,如果你想要一個動態的解決方案:
--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'
)
不錯,當你錄製你的代碼時有點錯誤,t2.SEATVACANT ='N' – Esperento57
@ Esperento57謝謝,現在修復。 – RBarryYoung
*差距和離島* - 例如[從表中查找「n」個連續的免費號碼)(http://dba.stackexchange.com/questions/36943/find-n-consecutive-free-numbers-from-table) –
如果這確實代表了劇院,那麼我懷疑有一排100個座位。所以你可能還需要考慮哪些座位在數字上是連續的,但不是彼此相鄰。 – sstan