sql - 在 sql 中使用 LAG 跳过特定行
问题描述
我有一个看起来像这样的表:
使用 SQL 中的 LAG 函数,我想仅对 star_date=end_date 的值执行 LAG,并获取过去的 start_date 记录,其中 start_date=end_date。我的茶几会有一个额外的列,如下所示:
我希望我的问题很清楚,任何帮助表示赞赏。
解决方案
您可以为这些值分配一个组并使用它:
select t.*,
(case when start_date = end_date
then lag(start_date) over (partition by (case when start_date = end_date then 1 else 0 end) order by start_date)
end) as prev_eq_start_date
from t;
或者:
select t.*,
(case when start_date = end_date
then lag(start_date) over (partition by start_date = end_date order by start_date)
end) as prev_eq_start_date
from t;
请注意,如果您的数据很大并且大多数行的日期不同,那么您可能会遇到资源问题。在这种情况下,一个额外的未使用的partition by
密钥可以帮助:
select t.*,
(case when start_date = end_date
then lag(start_date) over (partition by (case when start_date = end_date then 1 else 2 end), (case when start_date <> end_date then start_date end) order by start_date)
end) as prev_eq_start_date
from t;
这对结果没有影响,但它可以避免由于具有不同值的行太多而导致的资源错误。
推荐阅读
- python - 在python,sqlite3中更有效地将一个数据库表中的数据与另一个数据库表进行比较
- security - AzureDevOps YAML 管道 - 防止恶意使用生产服务连接
- javascript - NodeJS 中的导入导出调用顺序
- java - KeyBinding multiple keys pressed not working
- python - 使用 SHAP 解释 DNN 模型,但我的 summary_plot 仅显示每个特征的平均影响,并不包括所有特征
- wikipedia - 如何获取特定类别和等级的随机维基百科文章?
- python - 为一个键值分配多个值 - Python For Loop
- html - 我想用 link_to 滚动页面(ruby on rails)
- python - Discord.py slot 命令添加表情符号的移动动画
- python - Float 16 量化 Tflite 模型不适用于自定义模型?