34,576
社区成员
发帖
与我相关
我的任务
分享
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([ID] int,[姓名] varchar(1),[类型] varchar(4),[时间] datetime)
insert [tb]
select 1,'A','下井','2012-03-14 23:56:51' union all
select 2,'A','上井','2012-03-15 23:57:00' union all
select 3,'B','下井','2012-03-14 23:57:05' union all
select 4,'C','下井','2012-03-14 23:59:00' union all
select 5,'A','上井','2012-03-15 23:56:51' union all
select 6,'B','上井','2012-03-15 23:58:05'
go
select 姓名,时间 as 下井时间,
(select top 1 时间 from tb where 姓名=t.姓名 and 时间>t.时间 and 类型='上井' order by 时间) as 上井时间
from tb t
where 类型='下井'
/**
姓名 下井时间 上井时间
---- ----------------------- -----------------------
A 2012-03-14 23:56:51.000 2012-03-15 23:57:00.000
B 2012-03-14 23:57:05.000 2012-03-15 23:58:05.000
C 2012-03-14 23:59:00.000 NULL
(3 行受影响)
**/
select *
from 原始表 as a
left join 原始表 as b on a.姓名=b.姓名 and b.类型='上井' and ID=(select min(ID) from 原始表 where 姓名=b.姓名 and 类型=b.类型 and ID>a.ID)
where a.类型='下井'
select a.姓名,a.下井时间,b.上井时间
from tb a outer apply (select top 1 上井时间 from tb
where 姓名 = t.姓名 and 类型 = '上井' and id >= t.id order by id) b
where a.类型 = '下井'