如果时间戳较旧,则添加时间“08:05”后的秒数

cczfrluj  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(292)

我有一个sql代码(mysql),它返回一个mstate值的秒数,例如4

SELECT SUM(Seconds_In_State) From 
(SELECT 
    Time_Stamp, 
    MState,
   (-1 * TIMESTAMPDIFF(Minute, LEAD(Time_Stamp) OVER(ORDER BY Time_Stamp), Time_Stamp))
AS Seconds_In_State
FROM Mstate
WHERE DATE(`Time_Stamp`) = CURDATE() 
AND TIME(`Time_Stamp`) >= '08:05'  /*ShiftStart input tag*/
ORDER BY Time_Stamp) AS T
Where MState = 4;

结果将不包括从08:05到08:10的300秒,其中mstate为4。因为我看到时间戳>08:05。但是我想包括从08:05到08:10的时间,这里的状态是4。
所以它会找出从mstate为4的时间戳到下一个时间戳的时间。从08:05开始,加起来。如果mstate 4有时间戳08:00,则不包括在内。但是我想包括从08:05到08:10的秒数,其中mstate是4。因此,如果时间戳>=08:05之前的mstate值为4,则将08:05到08:10之间的秒数相加,以表示处于状态的秒数。
数据

|Time_Stamp              | MState |
|------------------------|------- |
|2021-04-23 07:50:00     |   3    |
|2021-04-23 08:00:00     |   4    |
|2021-04-23 08:10:00     |   1    |
|2021-04-23 08:22:00     |   2    |
|2021-04-23 08:30:00     |   3    |
|2021-04-23 08:40:00     |   4    |
|2021-04-23 08:50:00     |   1    |
|2021-04-23 09:01:00     |   2    |
|2021-04-23 09:10:00     |   3    |

当前代码的结果:| sum(秒|处于|状态)| | 600|
我想得到的结果是:
|总和(状态下的秒数)| | 900|

ql3eal8s

ql3eal8s1#

你似乎想要 lag() 以及执行时间表的比较:

SELECT SUM(Seconds_In_State) 
FROM (SELECT s.*,
             TIMESTAMPDIFF(Minute, 
                           GREATEST(LAG(Time_Stamp) OVER (ORDER BY Time_Stamp), addtime(cast(curdate() as datetime), '08:05')), 
                           Time_Stamp
                          ) AS Seconds_In_State
      FROM Mstate s
      WHERE DATE(Time_Stamp) = CURDATE() AND
            TIME(Time_Stamp) >= '08:05'  /*ShiftStart input tag*/
     ) s
WHERE MState = 4
ORDER BY Time_Stamp

相关问题