首页 > 解决方案 > 如何在组内使用 SQL Server 中的 LAG?

问题描述

以下是他们成为僵尸之前的不同人及其职业的列表。我需要在那个人变成僵尸之前找到职业。最后一个人变成了僵尸,然后又变回了动物园管理员,最后又变成了僵尸。在这种情况下,我只需要第一次僵尸转变之前的职业。

记录集:

Person    Occupation    Order_of_events
---------------------------------------
1         Lawyer        1
1         Dog Walker    2
1         Zoo Keeper    3
1         Zombie        4
1         Driver        5
2         Lifeguard     1
2         Zombie        2
3         Zoo Keeper    1
3         Zombie        2
3         Driver        3
3         Zombie        4

最后结果

Person    Occupation
---------------------
1         Zoo Keeper
2         Lifeguard
3         Zoo Keeper

我的尝试:

SELECT 
    person, occupation, Order_of_events,
    LAG(occupation, 1, 'Always a zombie') OVER (PARTITION BY person ORDER BY Order_of_events) AS [previous occupation]
FROM 
    table

我认为我的问题出在分区上,但我对如何选择僵尸所在的前一行感到困惑。

我正在使用 SQL Server 2017。

标签: sqlsql-server

解决方案


你实际上不需要lag()这个。但是窗口函数会有所帮助:

select top (1) with ties tprev.*
from t join
     t tprev
     on t.person = tprev.person 
    and t.Order_of_events = tprev.Order_of_events + 1
where t.occupation = 'Zombie'
order by row_number() over (partition by t.person order by t.Order_of_events);

推荐阅读