我有一个具有以下结构的SQL Server表
cod_turn (PrimaryKey)
taken (bit)
time (datetime)
和其他几个与问题无关的字段。我无法改变表格结构,因为该应用程序是由其他人制作的。
给出一个数值变量参数,我们假设这个例子为“3”,一个时间,我需要创建一个从那个时间开始查看的查询,它看起来没有标记的前3个连续记录作为“采取”。如果可能的话,我无法弄清楚如何在纯sql中进行查询。
PS:我接受了答案,因为它是正确的,但我对问题做了很糟糕的描述。我稍后会再提一个问题。看到答案的大小后感到愚蠢=)答案 0 :(得分:4)
SELECT TOP 3 * FROM table WHERE taken = 0 AND time>=@Time ORDER BY time
@Time是你传入的时间。
答案 1 :(得分:2)
假设当前版本的SQL Server并假设您已将“数字变量参数”命名为@top int
。注意:使用参数化TOP时,@top
周围的括号
SELECT TOP (@top)
cod_turn,
taken ,
time
FROM yourtable
WHERE Taken = 0 AND time>=@Time
ORDER BY time DESC
您也可以
with cte as
(
SELECT
ROW_NUMBER() over (order by time desc) rn
cod_turn,
taken ,
time
FROM yourtable
WHERE Taken = 0 AND time>=@Time
)
SELECT
cod_turn,
taken ,
time
FROM CTE
WHERE rn <= @top
ORDER BY time DESC
答案 2 :(得分:1)
SELECT TOP 3
*
FROM
table
WHERE
time >= @inserted_time
AND taken = 0
ORDER BY
cod_turn ASC
答案 3 :(得分:0)
select MT.*
from
(
select cod_turn, ROW_NUMBER() OVER (ORDER BY cod_turn) [RowNumber] -- or by time
from myTable
where taken = 0
and time >= @myTime
) T
inner join myTable MT on MT.cod_turn = T.cod_turn
where T.RowNumber < @myNumber
答案 4 :(得分:0)
select top 3 * from theTable where taken = 0 and time > theTime orderby time