where子句更改了datediff列的结果,我该如何解决?

时间:2018-07-23 19:38:33

标签: sql sql-server subquery datediff

我正在尝试获取st1 = 5时所经过的时间。这是我当前拥有的,这为我提供了每个状态更改的datediff时间。我的问题是,当我添加where st1 = 5子句时,datediff显示状态= 5的实例之间的时间差,而不是状态为5的经过时间。

select timestamp,st1,st2,st3,st4,
  datediff(second, timestamp, lead(timestamp) 
    over (order by timestamp)) as timediff
from A6K_status
Order By Timestamp DESC


+-----+-----+-----+-----+---------------------+----------+
| st1 | st2 | st3 | st4 | TimeStamp           | TimeDiff |
+-----+-----+-----+-----+---------------------+----------+
| 3   | 3   | 3   | 3   | 2018-07-23 07:51:06 |          |
+-----+-----+-----+-----+---------------------+----------+
| 5   | 5   | 5   | 5   | 2018-07-23 07:50:00 | 66       |
+-----+-----+-----+-----+---------------------+----------+
| 0   | 0   | 10  | 10  | 2018-07-23 07:47:19 | 161      |
+-----+-----+-----+-----+---------------------+----------+
| 5   | 5   | 5   | 5   | 2018-07-23 07:39:07 | 492      |
+-----+-----+-----+-----+---------------------+----------+
| 3   | 3   | 10  | 10  | 2018-07-23 07:37:48 | 79       |
+-----+-----+-----+-----+---------------------+----------+
| 3   | 3   | 10  | 10  | 2018-07-23 07:37:16 | 32       |
+-----+-----+-----+-----+---------------------+----------+

我试图求和station1的状态为5的时间。从上表(我现在拥有的)中,如果我可以对timediff求和,则st1 = 5可以正常工作。但是通过在查询中添加“ where st1 = 5”,可以使状态为5的实例之间的时间差为准。

任何帮助将不胜感激。我感觉非常接近我想要达到的结果。谢谢。

编辑 这就是我要实现的目标

+-----+------------+----------+
| st1 | TimeStamp  | TimeDiff |
+-----+------------+----------+
| 5   | 2018-07-23 | 558      |
+-----+------------+----------+

2 个答案:

答案 0 :(得分:1)

您将使用子查询(或CTE):

select sum(timediff)
from (select timestamp, st1, st2, st3, st4,
             datediff(second, timestamp, lead(timestamp) over (order by timestamp)) as timediff
      from A6K_status
     ) s
where st1 = 5;

答案 1 :(得分:0)

假设使用SQL Server,请尝试以下操作:

WITH SourceTable AS (
select TOP 100 PERCENT timestamp,st1,st2,st3,st4,
  datediff(second, timestamp, lead(timestamp) 
    over (order by timestamp)) as timediff
from A6K_status
Order By Timestamp DESC
)
SELECT SUM(timediff) as totaltimediff
WHERE st1 = 5