如何在Sql Server行中生成一系列不断变化的序列号

问题描述

我需要第一个 TSL 发件人与后续供应商以及下一个 TSL 到下一个后续发件人作为供应商的日期差异

enter image description here

期望的输出

enter image description here

解决方法

您可以通过计算每行上或之后的 'Vendor' 值的数量来为行分配一个分组。然后每个分组以 'Vendor' 结束,您可以在该组内使用窗口函数:

select t.*,(case when sender = 'vendor'
             then datediff(second,min(date) over (partition by grp),max(date) over (partition by grp)
                          ) / (24 * 60 * 60.0)
        end) as diff
from (select t.*,sum(case when sender = 'Vendor' then 1 else 0 end) over (order by id desc) as grp
      from t
     ) t;
,

因此您需要 TSL 更改为 Vendor 的天数差异。您可以按如下方式使用解析函数:

select t.*,case when sender = 'Vendor' 
            then DATEDIFF(hour,date,first_value(date) over (partition by rn - rn_s order by date) ) / 24.0 end as diff
  from
(select t.*,row_number() over (order by date) as rn,row_number() over (partition by sender order by date) as rn_s
  from yout_table t) t