在记录条目之前和之后查找
Find before and after entry of record
我有以下 table 来查找值前后的给定值。
例如,想要在给定列 col2
值 125
前后显示 1 个值。
Table:
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
是这样的吗?
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
我有以下 table 来查找值前后的给定值。
例如,想要在给定列 col2
值 125
前后显示 1 个值。
Table:
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
是这样的吗?
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