Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
值更改时对组的SQL查询_Sql_Sql Server - Fatal编程技术网

值更改时对组的SQL查询

值更改时对组的SQL查询,sql,sql-server,Sql,Sql Server,我的sql数据库中有以下数据 value timestamp 0 , 2018-03-21 14:32:24.417 0 , 2018-03-21 14:33:24.417 0 , 2018-03-21 14:34:24.417 4 , 2018-03-21 14:35:24.417 4 , 2018-03-21 14:36:24.417 0 , 2018-03-21 14:37:24.4

我的sql数据库中有以下数据

value                   timestamp
    0 ,   2018-03-21 14:32:24.417
    0 ,   2018-03-21 14:33:24.417
    0 ,   2018-03-21 14:34:24.417
    4 ,   2018-03-21 14:35:24.417
    4 ,   2018-03-21 14:36:24.417
    0 ,   2018-03-21 14:37:24.417
    0 ,   2018-03-21 14:38:24.417
我希望结果如下所示

value,               min timestamp , duration of how long value was in this value
    0 ,    2018-03-21 14:32:24.417,     2
    4 ,    2018-03-21 14:35:24.417,     1
    0 ,    2018-03-21 14:37:24.417,     1
我尝试使用lead函数,但由于值重复,所以它不起作用。非常感谢您在SQL Server上提供的任何帮助

SQL Server上的dbfiddle


DBFIDLE

请标记您的DBMS版本(包括Microsoft sql Server)请标记您的DBMS版本(包括Microsoft sql Server)我很乐意帮助。我很乐意帮助。
select value, min(timestamp), datediff(minute, min(timestamp), max(timestamp)) diff
from
    (select value, [timestamp], 
             sum(reset) over (order by timestamp) as grp
     from 
            (select value, [timestamp],
                    case when coalesce(lag(value) over (order by timestamp), '19000101') <> value then 1 end as reset
             from   tbl) t1
    ) t2
group by value, grp
GO
value | (No column name) | diff ----: | :------------------ | ---: 0 | 21/03/2018 14:32:24 | 2 4 | 21/03/2018 14:35:24 | 1 0 | 21/03/2018 14:37:24 | 1