注:我有一個正在運行的查詢,但正在尋找優化以在大型表上使用它。在特定值後跳過連續行
假設我有一個這樣的表:
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
我覺得這屬於在代碼審查原始查詢,不能疊加交流。這是工作代碼。 –