Sql 选择具有相同列值的行3次以上

Sql 选择具有相同列值的行3次以上,sql,sql-server,Sql,Sql Server,我有一张叫剧院的桌子 我想订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'

我有一张叫剧院的桌子


我想订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' 
--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'
    )

缺口和岛屿——例如,如果这真的代表了一个剧院,那么我怀疑是否有一排100个座位。因此,您可能还需要考虑哪些座位在数字上是相邻的,但在物理上不是相邻的。谢谢。它起作用了。。。。但这是一个静态的解决方案,我能动态地做吗。例如,对于x个连续的空座位,只需在录制代码时出现一个小错误,t2.SEATVACANT='N'@espernto57谢谢,现已修复。
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 ', 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'
    )