SQL Server : Filter for only the rows directly after a row containing specific text

标签 sql sql-server pandas indexing filter

我有一个包含以下列的表格

application_uuid
changed_at_utc
changed_by 
name

我想按 application_uuidchanged_at_utc 排序。然后,我只想过滤紧接在 application_status 具有文本“Ready for Scoring”

的行之后的行

使用 Python 和 Pandas,我会做这样的事情......

application_statuses = application_statuses.sort_values(['application_uuid', 'changed_at_utc'], ascending=[True, True]).reset_index(drop=True)
indexes = application_statuses[application_statuses['application_status']=='Ready for Scoring'].index + 1
next_statuses = application_statuses.ix[indexes]

如何使用 SQL 完成同样的事情?

最佳答案

根据您的解释,您可以使用 lead 函数来执行此操作。

select next_application_status,application_uuid,changed_at_utc,changed_by
from (select t.*,
      lead(application_status) over(order by application_uuid,changed_at_utc) as next_appliaction_status
      from tablename t
      ) t1
where application_status = 'Ready for Scoring'

如果必须对每个 application_uuid 执行此操作,请在 lead 中包含一个 partition by,如下所示。

select next_application_status,application_uuid,changed_at_utc,changed_by
from (select t.*,
      lead(application_status) over(partition by application_uuid order by changed_at_utc) as next_appliaction_status
      from tablename t
      ) t1
where application_status = 'Ready for Scoring'

如果您需要 application_status 准备评分之后的所有行,请获取该特定行的时间戳并选择所有其他较大的时间戳。这假设 application_uuid 最多有一行具有准备评分状态。

select application_status,application_uuid,changed_at_utc,changed_by
from (select t.*,
      max(case when application_status='Ready for Scoring' then changed_at_utc end) over(partition by application_uuid) as status_time
      from tablename t
      ) t1
where changed_at_utc > status_time

关于SQL Server : Filter for only the rows directly after a row containing specific text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42353662/

相关文章:

mysql - 如何在 SQL 连接中将类名分组在一起

MySQL计算多个列/表的最大值

sql - 如何在 sql server 中将 identity_insert 设置为 on

SQL Server范围索引的想法

python - 将 .isin 应用于 pandas 中每一行的有效方法

python - Pandas cut,如何标记正确的开放端点?

sql - 查询以在特定条件下重置以递增计数

sql - 在执行查询之前,如何从 Laravel 的查询构建器中获取原始查询字符串?

sql-server - 如何在公用表表达式 (CTE) 中引用同一服务器内多个数据库中的表?

python - 如何在Python中的列表的每个元素中添加常量字符串?