Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.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 server 使用行号()查询的连续行上的DateDiff()_Sql Server - Fatal编程技术网

Sql server 使用行号()查询的连续行上的DateDiff()

Sql server 使用行号()查询的连续行上的DateDiff(),sql-server,Sql Server,根据这些数据: create table #test (zone int, [date] datetime, active bit) insert into #test select 1, '2015-05-26 09:34:19.657', 0 insert into #test select 2, '2015-05-27 10:34:24.870', 0 insert into #test select 3, '2015-05-28 11:34:24.937', 0 insert into

根据这些数据:

create table #test (zone int, [date] datetime, active bit)

insert into #test select 1, '2015-05-26 09:34:19.657', 0
insert into #test select 2, '2015-05-27 10:34:24.870', 0
insert into #test select 3, '2015-05-28 11:34:24.937', 0
insert into #test select 3, '2015-05-29 12:41:33.743', 1
insert into #test select 2, '2015-05-30 09:41:38.933', 1
insert into #test select 3, '2015-06-01 08:41:39.013', 0
insert into #test select 1, '2015-06-04 11:44:42.840', 1
insert into #test select 2, '2015-06-05 19:44:42.840', 0
insert into #test select 3, '2015-06-06 16:44:42.893', 1
insert into #test select 2, '2015-06-07 15:50:15.783', 1
insert into #test select 1, '2015-06-08 06:50:55.270', 0
是否可以通过以下查询获取连续行的日期之间的差异:

WITH marked AS (
  SELECT
    *,grp = ROW_NUMBER() OVER (PARTITION BY zone ORDER BY [date])
        - ROW_NUMBER() OVER (PARTITION BY zone, active ORDER BY [date])
  FROM #test with (nolock)
)
select zone, date_from = min([date]), date_to = max([date]), active
from marked
group by zone, active, grp
ORDER BY zone, min([date])
目的是了解区域关闭的时间(字段“活动”等于0)。每次状态更改时,每个记录都会写入数据库

提前感谢您。

您可以尝试以下方法:

;WITH cte AS(
    SELECT zone, date, active, ROW_NUMBER() OVER(PARTITION BY zone ORDER BY date) as rowNo
    FROM #test
)
SELECT cur.zone, cur.active as curStatus, prev.active as prevStatus, cur.date, prev.date, DATEDIFF(MINUTE,prev.date, cur.date) as diffInMinutes 
FROM cte as cur
INNER JOIN cte as prev
        ON cur.zone = prev.zone
        AND cur.rowNo-1 = prev.rowNo

假设您使用的是sql server 2012或更新版本,也可以使用
lead
功能。这还有一个额外的优点,即您可以为当前处于非活动状态的区域提供默认的当前时间。 铅的例子:

select *,  LEAD([date],1,GETDATE()) over (partition by zone order by [date]) nextdate from #test
同样,您可以在[Date]和lead Date上使用datediff一次性获得工期

将活动=0的持续时间结果相加,总持续时间(以分钟为单位)的组合结果如下:

select SUM(Duration) Duration, Zone from
(
   select *, DATEDIFF(minute, [date], LEAD([date],1,GETDATE()) over (partition by zone order by [date])) Duration from #test
) z
where active = 0
group by Zone

什么版本的SQL Server?由于他可以使用窗口功能,但不能使用
LAG
,我猜SQL Server 2008(R2)无法测试,因为我的SQL Server版本无法识别函数“Lead”。SQL Server 2012及更高版本支持该函数。