【问题标题】:capture reoccurring seventh day in new column在新列中捕获重复出现的第七天
【发布时间】:2021-08-19 16:55:33
【问题描述】:

我有下表...

run_dt   check_type  curr_cnt
 6/1/21    ALL         50
 5/31/21   ALL         25
 5/26/21   ALL         43
 5/25/21   ALL         70
 6/1/21    SUB         23
 5/25/21   SUB         49

我想从 run_dt 捕获 7 天后 check_type 的值。上一个工作日的值是多少。

类似...

run_dt   check_type  curr_cnt  prev_nt
 6/1/21    ALL         50        70
 5/31/21   ALL         25        
 5/26/21   ALL         43
 5/25/21   ALL         70
 6/1/21    SUB         23        49
 5/25/21   SUB         49

我可以使用lead/lagCTE 吗?

这里最好的选择是什么,感谢反馈。

【问题讨论】:

  • 如果您每天都有一行,您可以使用LEAD/LAG。您可以使用 Tally 或日历表为此创建行,LEAD/LAG,然后过滤掉没有数据的行。您要竞选的日期范围有多大。
  • 是否有可能不存在 7 天前的一行,如果存在,该值应该为 null 还是其他?

标签: sql-server common-table-expression lag lead


【解决方案1】:

您可以将表连接到自身:

SELECT
  a.run_dt,
  a.check_type,
  a.curr_cnt,
  b.curr_cnt as prev_nt
from table a
left join table b on b.run_dt = dateadd(d,-7,a.run_dt)

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多