查找行更改并输出到表

时间:2016-06-29 12:48:59

标签: sql select reporting-services sql-server-2008-r2 ssrs-2008-r2

我有一个具有以下结构的SQL Server表:

id     TransDate            PartType
======================================
1     2016-06-29 10:23:00   A1
2     2016-06-29 10:30:00   A1
3     2016-06-29 10:32:00   A2
4     2016-06-29 10:33:00   A2
5     2016-06-29 10:35:00   A2
6     2016-06-29 10:39:00   A3
7     2016-06-29 10:41:00   A4

我需要一个SELECT语句,该语句将输出一个查找PartType中的更改的表,看起来像这样(出于SSRS目的):

PartType   StartTime             EndTime       
=======================================================
A1         2016-06-29 10:23:00   2016-06-29 10:32:00
A2         2016-06-29 10:32:00   2016-06-29 10:39:00
A3         2016-06-29 10:39:00   2016-06-29 10:41:00
A4         2016-06-29 10:41:00   NULL

请注意StartTime始终从最后EndTime开始,除非它是表格中的第一条记录。

我的SELECT陈述应该是什么?我似乎无法得到预期的结果。

编辑:我正在使用SQL Server 2008 R2;我应该指明一下。

2 个答案:

答案 0 :(得分:2)

嗯,这是一种使用outer applygroup by的方法:

select t1.PartType, min(t1.TransDate) as StartTime, t2.TransDate
from t t1
outer apply
     (select top 1 t2.*
      from t t2
      where t2.PartType <> t1.PartType and t2.TransDate > t1.TransDate
      order by t2.TransDate asc
     ) t2
group by t1.PartType, t2.TransDate;

答案 1 :(得分:1)

使用SQL Server 2012及更高版本,您可以使用:

declare @t table (id int, transdate datetime2(0), parttype char(2))

insert @t
values
(1,     '2016-06-29 10:23:00',   'A1'),
(2,     '2016-06-29 10:30:00',   'A1'),
(3,     '2016-06-29 10:32:00',   'A2'),
(4,     '2016-06-29 10:33:00',   'A2'),
(5,     '2016-06-29 10:35:00',   'A2'),
(6,     '2016-06-29 10:39:00',   'A3'),
(7,     '2016-06-29 10:41:00',   'A4')

;with x as (
select *, row_number() over(partition by parttype order by transdate) rn
from @t
)
select parttype, transdate starttime, lead(transdate) over (order by transdate) from x where rn = 1