现在有一个sql server数据表,有时间列以及多台设备的实时电流大小,电流每两分钟采集一次,现在假设规定设备电流大于100时处于工作状态,大于0小于100为通电但不工作(待机状态),等于0为停机状态,但由于工作时其他设备影响,电流会出现波动,即使在运行状态也可能出现一段时间里电流小于100的情况,但此时设备仍处于运行状态(图中蓝色部分),所以规定电流小于100的时间不超过半小时即为运行状态,超过半小时或者半小时内待机时间超过运行时间则为待机状态,想要计算出设备一天内(或者规定时间内)工作时长、停机时长、待机时长
sql server时间处理问题
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- AitTech 2024-08-28 17:19关注
WITH StateChanges AS ( SELECT DeviceID, TimeStamp, Current, CASE WHEN Current > 100 THEN 'Working' WHEN Current > 0 AND Current <= 100 THEN 'Standby' ELSE 'Off' END AS State, LEAD(TimeStamp) OVER (PARTITION BY DeviceID ORDER BY TimeStamp) AS NextTimeStamp, LEAD(Current) OVER (PARTITION BY DeviceID ORDER BY TimeStamp) AS NextCurrent FROM DeviceCurrent WHERE -- 假设我们计算特定日期的一天的数据 CAST(TimeStamp AS DATE) = '2024-08-28' ), StateDurations AS ( SELECT DeviceID, TimeStamp AS StartTime, CASE WHEN NextTimeStamp IS NULL THEN CAST('23:59:59' AS TIME) ELSE DATEADD(MINUTE, 2, CAST(TimeStamp AS TIME)) -- 假设每次记录间隔为2分钟 END AS EndTime, State, CASE WHEN LEAD(State) OVER (PARTITION BY DeviceID ORDER BY TimeStamp) IS NULL OR State <> LEAD(State) OVER (PARTITION BY DeviceID ORDER BY TimeStamp) THEN DATEDIFF(MINUTE, TimeStamp, CASE WHEN NextTimeStamp IS NULL THEN CAST('2023-04-01 23:59:59' AS DATETIME) ELSE DATEADD(MINUTE, 2, CAST(TimeStamp AS DATETIME)) END) ELSE 0 END AS DurationInMinutes FROM StateChanges ), AggregatedStates AS ( SELECT DeviceID, State, SUM(DurationInMinutes) AS TotalDurationInMinutes FROM StateDurations GROUP BY DeviceID, State ), FinalResults AS ( SELECT DeviceID, SUM(CASE WHEN State = 'Working' THEN TotalDurationInMinutes ELSE 0 END) AS WorkingHours, SUM(CASE WHEN State = 'Off' THEN TotalDurationInMinutes ELSE 0 END) AS OffHours, SUM(CASE WHEN State = 'Standby' THEN TotalDurationInMinutes ELSE 0 END) AS StandbyHours FROM AggregatedStates GROUP BY DeviceID ) SELECT * FROM FinalResults;
解决 无用评论 打赏 举报
悬赏问题
- ¥15 ul做导航栏格式不对怎么改?
- ¥20 用户端如何上传图片到服务器和数据库里
- ¥15 现在研究生在烦开题,看了一些文献,但不知道自己要做什么,求指导。
- ¥30 vivado封装时总是显示缺少一个dcp文件
- ¥100 pxe uefi启动 tinycore
- ¥15 我pycharm运行jupyter时出现Jupyter server process exited with code 1,然后打开cmd显示如下
- ¥15 可否使用carsim-simulink进行四轮独立转向汽车的联合仿真,实现四轮独立转向汽车原地旋转、斜向形式、横移等动作,如果可以的话在carsim中如何进行相应设置
- ¥15 Caché 2016 在Java环境通过jdbc 执行sql报Parameter list mismatch错误,但是同样的sql使用连接工具可以查询出数据
- ¥15 疾病的获得与年龄是否有关
- ¥15 opencv.js内存,CPU飙升