使用row_number()

时间:2015-06-24 20:59:11

标签: 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 #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)。每次状态更改时,每条记录都写在数据库中。

提前谢谢。

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

[Table]

答案 1 :(得分:0)

假设您使用的是sql server 2012或更高版本,您还可以使用lead功能。这具有额外的优势,您可以将当前时间作为当前非活动区域的默认值。 铅的例子:

select *,  LEAD([date],1,GETDATE()) over (partition by zone order by [date]) nextdate from #test

以同样的方式,您可以在[日期]和提前日期使用datediff一次性获得持续时间。

将active = 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