python - 在 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
区别是以秒为单位的中断时间。数据集将来会增长,所以我想创建一个自动计算的工作。
在我的尝试中我失败了。我希望你能帮我计算中断时间。我先谢谢了。
此致
基督教
解决方案
嗯。. . 使用累积最大值来获取每行的开始日期。然后过滤到结束日期并计算差异:
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;
推荐阅读
- javascript - 如何在 Typescript 中导入 Javascript 模块
- android - 即使明显错误,旋转矢量传感器也能保持高精度报告
- c# - 如何使用 Entity Framework Core 2.0 检索 JSON 存储过程的结果?
- uwp - 用于 Window Store 8.1 应用程序/UWP 应用程序开发的应用程序内帮助演练 API
- amazon-web-services - 使用 boto3 将来自 KinesisVideoStream 的流式视频保存到本地文件
- statusbar - iOS 个人热点让导航控制器崩溃
- jquery - 实时更新引导日期选择器的 DaysOfWeekDisabled
- sql - spark sql 是否区分大小写?
- botframework - 功能上的 Botframework v4
- ios - 在片段着色器中读取像素数据