日期:2014-05-17 浏览次数:20478 次
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (工号 nvarchar(18),姓名 nvarchar(6),时间 datetime)
insert into [TB]
select 'IHH101736','張二賀','2010-12-31 00:00:00' union all
select 'IHH101736','張二賀','2011-07-01 00:00:00' union all
select 'IHH101736','張二賀','2013-01-01 00:00:00' union all
select 'IHH101741','艾維平','2011-01-01 00:00:00' union all
select 'IHH102052','吳細波','2010-12-01 00:00:00' union all
select 'IHH102052','吳細波','2011-01-01 00:00:00'
select * from [TB]
;WITH TT
AS(SELECT ROW_NUMBER() OVER(PARTITION BY 工号 ORDER BY 时间) AS num,* FROM TB)
SELECT A.工号,A.姓名,A.时间,DATEDIFF(dd,B.时间,A.时间) AS 时间间隔
FROM TT A
left JOIN TT B ON A.工号 = B.工号 AND A.num = b.num + 1
/*
工号 姓名 时间 时间间隔
IHH101736 張二賀 2010-12-31 00:00:00.000 NULL
IHH101736 張二賀 2011-07-01 00:00:00.000 182
IHH101736 張二賀 2013-01-01 00:00:00.000 550
IHH101741 艾維平 2011-01-01 00:00:00.000 NULL