注:我有一个正在运行的查询,但正在寻找优化以在大型表上使用它。在特定值后跳过连续行
假设我有一个这样的表:
id session_id value
1 5 7
2 5 1
3 5 1
4 5 12
5 5 1
6 5 1
7 5 1
8 6 7
9 6 1
10 6 3
11 6 1
12 7 7
13 8 1
14 8 2
15 8 3
我想所有行值为1有一个例外的ID的: 跳跃组,值1直接遵循相同的session_id内的值7。
基本上我会寻找值为1的组,直接跟随由session_id限制的值7,并忽略这些组。然后我显示所有剩余的值1行。
所需的输出显示的ID:
5
6
7
11
13
我花了一些灵感来自于this post并结束了这段代码:
declare @req_data table (
id int primary key identity,
session_id int,
value int
)
insert into @req_data(session_id, value) values (5, 7)
insert into @req_data(session_id, value) values (5, 1) -- preceded by value 7 in same session, should be ignored
insert into @req_data(session_id, value) values (5, 1) -- ignore this one too
insert into @req_data(session_id, value) values (5, 12)
insert into @req_data(session_id, value) values (5, 1) -- preceded by value != 7, show this
insert into @req_data(session_id, value) values (5, 1) -- show this too
insert into @req_data(session_id, value) values (5, 1) -- show this too
insert into @req_data(session_id, value) values (6, 7)
insert into @req_data(session_id, value) values (6, 1) -- preceded by value 7 in same session, should be ignored
insert into @req_data(session_id, value) values (6, 3)
insert into @req_data(session_id, value) values (6, 1) -- preceded by value != 7, show this
insert into @req_data(session_id, value) values (7, 7)
insert into @req_data(session_id, value) values (8, 1) -- new session_id, show this
insert into @req_data(session_id, value) values (8, 2)
insert into @req_data(session_id, value) values (8, 3)
select id
from (
select session_id, id, max(skip) over (partition by grp) as 'skip'
from (
select tWithGroups.*,
(row_number() over (partition by session_id order by id) - row_number() over (partition by value order by id)) as grp
from (
select session_id, id, value,
case
when lag(value) over (partition by session_id order by session_id) = 7
then 1
else 0
end as 'skip'
from @req_data
) as tWithGroups
) as tWithSkipField
where tWithSkipField.value = 1
) as tYetAnotherOutput
where skip != 1
order by id
这给了想要的结果,但有4个选择块我认为在大型表上使用它效率太低。
有没有更干净,更快捷的方法来做到这一点?
看看LAG:https://docs.microsoft.com/en-us/sql/t-sql/functions/lag-transact-sql您可以查看上一行。 – Leonidas199x
他们用'LAG'在@ Leonidas199x – scsimon
我觉得这属于在代码审查原始查询,不能叠加交流。这是工作代码。 –