2015-10-19 42 views
0

我有一個表中調用「TableAvailable」表格ID int和可作爲SMALLINT(0,1)這樣獲取序列順序的行的x量

TableID |Available 
1  |1 
2  |0 
3  |0 
4  |1 
5  |1 
6  |1 
7  |0 
8  |1 

我需要一個SQL,我可以選擇第一3表,該表一起,在我們的例子應該是4,5,6這是第一個3行什麼是可一起

+0

什麼版本的SQL Server?而且,第一列中的ID是否連續沒有間隙? –

回答

2

您可以通過使用獲得連續ID的所有組:

select min(tableid), max(tableid) 
from (select ta.*, 
      (row_number() over (order by tableid) - 
       row_number() over (partition by available order by tableid) 
      ) as grp 
     from tableavailable ta 
    ) ta 
where available = 1 
group by grp; 

然後,加入having count(*) >= 3 order by min(tableid)將獲得第一。

但是,更快的方法是查看下兩個記錄的可用性。在SQL Server 2012+,你可以使用lead()

select top 1 tableid_1, tableid_2, tableid_3 
from (select ta.*, 
      lead(available) over (order by tableid) as available_1, 
      lead(available, 2) over (order by tableid) as available_2, 
      lead(tableid) over (order by tableid) as tableid_1, 
      lead(tableid, 2) over (order by tableid) as tableid_2, 
     from tableavailable ta 
    ) ta 
where available = 1 and available_1 = 1 and available_2 = 1 
order by tableid; 
0

假設你只會永遠需要3做到這一點,假設TABLEID的是連續的,沒有空位......都可能是壞的假設......

SELECT Top 1 A.TableID, B.TableID, C.TableId 
FROM TableAvailable A 
LEFT JOIN tableAvailable B 
on A.ID = B.ID+1 
LEFT JOIn tableAvailable C 
on A.ID = B.ID+2 
WHERE A.Available = 1 and B.Availabe=1 and C.Available=1 
order by tableID asc 
0

您沒有指定輸出的格式,所以我假定您需要表中的行。這裏是一個可能的解決方案:

WITH answer AS (
select MIN(TableID) as found 
from TableAvailable as T1 
where Available = 1 
and 1 = (select Available 
     from TableAvailable as T2 
     where T2.TableID = T1.TableID + 1 
     ) 
and 1 = (select Available 
     from TableAvailable as T3 
     where T3.TableID = T1.TableID + 2 
     )   
) 
select * 
from TableAvailable 
join answer 
on TableID = found 
or TableID = found + 1 
or TableID = found + 2 

在這裏工作小提琴:http://sqlfiddle.com/#!3/06a74/2