首页 > 解决方案 > 在 T-SQL 中迭代行

问题描述

我尝试计算 SQL Server 中两个日期之间的差异。也就是说startdate,如果“中断”= 1 和“自动”= 0。这enddate是下一个日期,其中“中断”= 0 和“自动”= 1。我尝试使用该功能

DATEDIFF(startdate, enddate, ...)

例如我有以下数据:

ID   Date                      Interrupt    Automatic
-------------------------------------------------------
15   2020-07-06 09:56:35.630        0           1
14   2020-07-06 09:56:35.630        1           0
13   2020-07-06 09:56:33.407        1           1
12   2020-07-06 09:56:32.490        1           0
11   2020-07-06 09:56:30.073        0           1
10   2020-07-06 09:56:30.073        1           1
 9   2020-07-06 09:56:29.070        1           1
 8   2020-07-06 09:56:26.867        1           1
 7   2020-07-06 09:56:26.867        1           0
 6   2020-07-06 09:56:25.863        0           1
 5   2020-07-06 09:56:23.897        1           0
 4   2020-07-06 09:56:23.500        1           1
 3   2020-07-06 09:56:19.340        1           0
 2   2020-07-06 09:56:17.003        0           1
 1   2020-07-06 09:56:16.220        1           1

在此示例中,我想计算 ID 为 3 的行与 ID 为 6 的行之间的差异 --> DATEDIFF(ID3.Date, ID6.Date, Milliseconds)

本例中的下一个案例,ID 11 和 ID 7 的日期之间的差异 --> DATEDIFF(ID7.Date, ID11.Date, Milliseconds)

结果应该是这样的:

  ID   Date                      Interrupt    Automatic    Interrupttime
    ------------------------------------------------------------------
15   2020-07-06 09:56:35.630        0           1
12   2020-07-06 09:56:32.490        1           0             3,140
11   2020-07-06 09:56:30.073        0           1
 7   2020-07-06 09:56:26.867        1           0             3,206         
 6   2020-07-06 09:56:25.863        0           1
 3   2020-07-06 09:56:19.340        1           0             6,523 

区别是以秒为单位的中断时间。数据集将来会增长,所以我想创建一个自动计算的工作。

在我的尝试中我失败了。我希望你能帮我计算中断时间。我先谢谢了。

此致

基督教

标签: pythonsqlsql-serverdatabasetsql

解决方案


嗯。. . 使用累积最大值来获取每行的开始日期。然后过滤到结束日期并计算差异:

select t.*, datediff(millisecond, start_date, date)
from (select t.*,
             max(case when interrupt = 1 and automatic = 0 then date end) over (order by id) as start_date
      from t
     ) t
where interrupt = 0 and automatic = 1;

推荐阅读