Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 按顺序获取x行数_Sql_Sql Server - Fatal编程技术网

Sql 按顺序获取x行数

Sql 按顺序获取x行数,sql,sql-server,Sql,Sql Server,我有一个表,将“TableAvailable”TableID称为int,并将其称为smallInt(0,1),如下所示 TableID |Available 1 |1 2 |0 3 |0 4 |1 5 |1 6 |1 7 |0 8 |1 我需要一个sql,我可以选择一起的前3个表,在我们的示例中,它应该是4,5,6,这是一起可用的前3行 select min(tableid), max(table

我有一个表,将“TableAvailable”TableID称为int,并将其称为smallInt(0,1),如下所示

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

我需要一个sql,我可以选择一起的前3个表,在我们的示例中,它应该是4,5,6,这是一起可用的前3行

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()


假设你只需要做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

您没有指定输出的格式,因此我假设您需要表中的行。以下是一个可能的解决方案:

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

在这里工作:

什么版本的SQL Server?并且,第一列中的ID是否总是在一行中,没有间隙?
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