在记录输入之前和之后查找

时间:2018-10-11 09:30:31

标签: sql-server sql-server-2008-r2

我有下表在值之前和之后找到给定值。

例如,要显示给定列col2125之前和之后的1个值。

表格:

CREATE TABLE PreTest1
(
 col1 int,
 col2 int,
 col3 date,
 col4 time
);

样本数据:

insert into PreTest1 values(111,124,'2018-01-01','00:10:11'),
                          (111,124,'2018-01-01','00:10:12'),
                          (111,122,'2018-01-01','00:10:17'),
                          (111,125,'2018-01-01','00:10:16'),
                          (111,125,'2018-01-01','00:10:13'),
                          (111,123,'2018-01-01','00:10:19'),
                          (111,130,'2018-01-01','00:10:18'),
                          (111,123,'2018-01-01','00:10:17'),
                          (111,121,'2018-01-01','00:09:11');

查询:

WITH C1 AS
(
    SELECT ROW_NUMBER() OVER(order by col2,col3,col4) rn,*
    FROM PreTest1
)
SELECT * FROM 
(

    SELECT * FROM C1 WHERE rn IN (SELECT rn FROM C1 WHERE col2 = '125')
    UNION 
    SELECT * FROM C1 WHERE rn IN ( SELECT rn - 1 FROM C1 WHERE col2 = '125') 
    UNION       
    SELECT * FROM C1 WHERE rn IN ( SELECT rn + 1 FROM C1 WHERE col2 = '125') 
) a

预期产量

col1        col2        col3       col4
----------- ----------- ---------- ----------------
111         124         2018-01-01 00:10:12.0000000
111         125         2018-01-01 00:10:16.0000000
111         123         2018-01-01 00:10:17.0000000

1 个答案:

答案 0 :(得分:1)

像这样吗?

WITH TMP1 AS
(
    SELECT ROW_NUMBER() OVER(partition by col1, col2 order by col3 desc, col4 desc) rang1, *
    FROM PreTest1
),
TMP2 as (
select ROW_NUMBER() OVER(order by col3 , col4, col2 desc) rang2, * 
from tmp1 where rang1=1
),
ValueRang as 
(
SELECT rang2 Position FROM TMP2 where col2=125
)
select * from tmp2
cross apply ValueRang
where tmp2.rang2 between Position-1 and Position + 1