sql - 如何在组内使用 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。
解决方案
你实际上不需要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);
推荐阅读
- javascript - 无法加载插件 vue/Eslint 中断
- javascript - 在 raw-body 之后使用 express.json()
- azure-data-factory - 如何将整数存储到 Azure 数据工厂中的变量?
- c++ - libcurl 仅用换行替换回车 + 换行
- django-models - 如何从模型中获取 Django Shell 中的 is_active = False?
- python - 全局声明之前使用的 Python 3.7.3 SyntaxError 变量
- operating-system - Alpine linux 操作系统版本控制
- php - 带有自定义主题的 Wordpress 的 504 网关超时错误
- apache - 即使安装在正确的位置,Apache 也找不到目录
- javascript - 在Openedx Based Project中,Xblock自定义需要在javascript的textarea中添加CKEditor