Find Row Changes and Output to Table

荒凉一梦 提交于 2019-12-12 00:42:55

问题


I have an SQL Server table of the following structure:

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

I need a SELECT statement that will output a table that finds the changes in PartType, and that looks like this (for SSRS purposes):

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

Note that the StartTime always picks up from the last EndTime, unless it's the first record in the table.

What should my SELECT statement be? I can't seem to get the intended results.

EDIT: I'm using SQL Server 2008 R2; I should've specified that.


回答1:


With SQL Server 2012 and later, you can use this:

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



回答2:


Hmmm, here is one method using outer apply and group 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;


来源:https://stackoverflow.com/questions/38100062/find-row-changes-and-output-to-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!