我想计算连续行的时间差,其中0是机器开始时间,1是机器结束时间。下面是我的代码和链接截图,这是不正确的代码。您可以重新生成此代码。
输出错误:https://drive.google.com/file/d/1zbjprruswi5nobynnwm8mfrljbwpbnv5/view?usp=sharing
WITH TimeDuration (PumpID, PumpNo, Value, logdate, logtime,PlantType)
AS
(
SELECT
PumpID, PumpNo, Value, CONVERT(date, vPumpRunStatus.Date),
MAX(vPumpRunStatus.time), PlantType
FROM
vPumpRunStatus
INNER JOIN
DIR ON vPumpRunStatus.PumpID = DIR.ID
GROUP BY
PumpID, PumpNo, Value, vPumpRunStatus.Date,
DATEPART(Minute, vPumpRunStatus.time), PlantType
)
SELECT
t1.PumpID, t1.PumpNo, t1.logdate, t2.Value,
t1.logtime AS StartTime, (t2.logtime) AS EndTime,
CONVERT(varchar(5), DATEDIFF(M, t1.logtime, (t2.logtime)) / 3600) + ':' +
CONVERT(varchar(5), DATEDIFF(M, t1.logtime, (t2.logtime)) % 3600 / 60) + ':' +
CONVERT(varchar(5), (DATEDIFF(M, t1.logtime, (t2.logtime)) % 60)) AS TimeDifference
FROM
(SELECT *
FROM TimeDuration
WHERE Value = 0
AND PumpID = 91
AND PlantType = 3 ) t1
INNER JOIN
(SELECT *
FROM TimeDuration
WHERE value = 1
AND PumpID = 91
AND PlantType = 3) t2 ON t2.PumpID = t1.PumpID
所需的输出'screenshot2'也附后。
https://drive.google.com/file/d/1-zbzit3rm_gy3rrp2lzfwft-d42fjxgq/view?usp=sharing
1条答案
按热度按时间x7yiwoj41#
也许一个好的解决方案是尝试使用lag sql函数:https://www.sqlservertutorial.net/sql-server-window-functions/sql-server-lag-function/
使用lag,可以找到上一条记录的值。之后,使用cte,您可以在同一行中有较旧和较新的记录,并计算时间差。
如果我对你的问题理解正确,这将是你的解决办法