--> --> (Roy)生成測試數據
 
if not object_id('Tempdb..#T') is null
drop table #T
Go
Create table #T([姓名] nvarchar(1),[日期] nvarchar(8),[上班时间] nvarchar(5),[下班时间] nvarchar(5))
Insert #T
select N'a','20090601','07:40','12:05' union all
select N'a','20090601','14:20','18:01' union all
select N'b','20090601','07:49',null
Go
declare @s nvarchar(4000),@i nvarchar(4)
set @s=''
Select top 1 @i=count(*) from #T group by [姓名],[日期] order by count(*) desc
while @i>0
select @s=',[上班时间]=max(case when con='+@i+' then [上班时间] else '''' end),[下班时间]=max(case when con='+@i+' then isnull([下班时间],'''') else '''' end)'+@s,@i=@i-1
exec('select [姓名],[日期]'+@s+' from (select *,con=(select count(*) from #T where [姓名]=a.[姓名] and [日期]=a.[日期] and [上班时间]<=a.[上班时间]) from #T a)t group by [姓名],[日期]')
(3 行受影响)
姓名   日期       上班时间  下班时间  上班时间  下班时间
---- -------- ----- ----- ----- -----
a    20090601 07:40 12:05 14:20 18:01
b    20090601 07:49             (2 行受影响)