我需要帮助分析从 Sql 检索的数据
我的要求是这样的:
我有一个返回记录集的视图,其中对于 DeviceStatus 列值的每次更改,我将“Flag”字段设置为 1。 这样我就可以计算出该状态的总持续时间。问题是当持续时间“溢出”到下一小时时,因为我想要新一小时的另一条记录。
查询是这样的。
SELECT EventTime,DeviceStatus, CASE WHEN DeviceStatus = LAG(DeviceStatus)
OVER (ORDER BY EventTime) THEN 0 ELSE 1 END AS Flag
FROM [EventSourcing].[Fact].[Operations]
WHERE (DeviceName LIKE '*****')
AND DateID in (20241129,20241130)
order by 1
一个具体案例是这样的,在 18:15:07 发生了一个状态变化,一直持续到第二天 04:44:02
活动时间 | 设备状态 | 旗帜 |
---|---|---|
2024-11-29 18:08:49.8317093 | 1000 | 0 |
2024-11-29 18:08:57.3539314 | 1000 | 0 |
2024-11-29 18:09:05.1978502 | 1000 | 0 |
2024-11-29 18:09:08.6673125 | 1000 | 0 |
2024-11-29 18:09:16.1053403 | 2000 | 1 |
2024-11-29 18:09:27.3567976 | 2000 | 0 |
2024-11-29 18:09:57.3746556 | 2000 | 0 |
2024-11-29 18:15:07.8193011 | 3004 | 1 |
2024-11-30 04:44:02.7432369 | 2000 | 1 |
2024-11-30 04:45:21.7130785 | 2016 | 1 |
2024-11-30 04:46:36.8242106 | 2000 | 1 |
2024-11-30 04:53:58.1847945 | 1000 | 1 |
2024-11-30 04:56:05.6637439 | 1000 | 0 |
2024-11-30 04:56:28.4035914 | 1000 | 0 |
我希望是这样的
活动时间 | 设备状态 | 旗帜 |
---|---|---|
2024-11-29 18:08:49.8317093 | 1000 | 0 |
2024-11-29 18:08:57.3539314 | 1000 | 0 |
2024-11-29 18:09:05.1978502 | 1000 | 0 |
2024-11-29 18:09:08.6673125 | 1000 | 0 |
2024-11-29 18:09:16.1053403 | 2000 | 1 |
2024-11-29 18:09:27.3567976 | 2000 | 0 |
2024-11-29 18:09:57.3746556 | 2000 | 0 |
2024-11-29 18:15:07.8193011 | 3004 | 1 |
2024-11-29 19:00:00.0000000 | 3004 | 0 |
2024-11-29 20:00:00.0000000 | 3004 | 0 |
2024-11-29 21:00:00.0000000 | 3004 | 0 |
2024-11-29 22:00:00.0000000 | 3004 | 0 |
2024-11-29 23:00:00.0000000 | 3004 | 0 |
2024-11-30 00:00:00.0000000 | 3004 | 0 |
2024-11-30 01:00:00.0000000 | 3004 | 0 |
2024-11-30 02:00:00.0000000 | 3004 | 0 |
2024-11-30 03:00:00.0000000 | 3004 | 0 |
2024-11-30 04:00:00.0000000 | 3004 | 0 |
2024-11-30 04:44:02.7432369 | 2000 | 1 |
2024-11-30 04:45:21.7130785 | 2016 | 1 |
2024-11-30 04:46:36.8242106 | 2000 | 1 |
2024-11-30 04:53:58.1847945 | 1000 | 1 |
2024-11-30 04:56:05.6637439 | 1000 | 0 |
2024-11-30 04:56:28.4035914 | 1000 | 0 |
我必须输入记录吗? 我不知道该怎么做。 感谢任何可以帮助我的人。
安德里亚
--Use event time if it exists for a given hour,otherwise use generated exact hour
with d as (
select cast('2024-11-29' as datetime) as dte
union all
select dateadd(hour, 1, dte)
from d
where dateadd(hour, 1, dte) < '2024-12-01'
)
select isnull(o.EventTime,d.dte) as EventTime
from d
LEFT JOIN Operations o on d.dte=DATEADD(HH,DATEPART(HH,o.EventTime),CAST(CAST(o.EventTime AS DATE) AS DATETIME))
option (maxrecursion 0);