我有下面描述的表,我需要從中選擇[Value]更大的所有行,例如至少比前一行中的[Value]要多5點(按[Id ])。與[ID] 1的第一行開始,所需的輸出將是:T-SQL - 具有較大值的下一行,連續
[Id] [Value]
---------------
1 1
4 12
8 21
代碼:
declare @Data table
(
[Id] int not null identity(1, 1) primary key,
[Value] int not null
);
insert into @Data ([Value])
select 1 [Value]
union all
select 5
union all
select 3
union all
select 12
union all
select 8
union all
select 9
union all
select 16
union all
select 21;
select [t1].*
from @Data [t1];
編輯:
因此,基於JNevill的和Hogan的答案,我這樣結束:
;with [cte1]
as (
select [t1].[Id],
[t1].[Value],
cast(1 as int) [rank]
from @Data [t1]
where [t1].[Id] = 1
union all
select [t2].[Id],
[t2].[Value],
cast(row_number() over (order by [t2].id) as int) [rank]
FROM [cte1] [t1]
inner join @Data [t2] on [t2].[value] - [t1].[value] > 5
and [t2].[Id] > [t1].[Id]
where [t1].[rank] = 1
)
select [t1].[Id],
[t1].[Value]
from [cte1] [t1]
where [t1].[rank] = 1;
這是工作。 Alan Burstein答案也正確(但僅適用於MSSQL 2012+ - 由於LAG fc)。我會做一些性能測試(我在2016版),並會看到我的真實數據(大約有3千萬條記錄)的性能。
爲什麼'16'不是結果的一部分? '16-9> 5' –
因爲它必須與之前創建的Value進行比較,它是12. – paYa
對於'16',當我們通過'ID'命令時,以前的值是'9' –