日期:2014-05-18 浏览次数:20570 次
--> 测试数据:[tbl]
if object_id('[tbl]') is not null drop table [tbl]
create table [tbl]([workid] varchar(5),[recdate] date,[rectime] time)
insert into tbl
select '02109','2012-3-1','07:36' union all
select '02109','2012-3-1','09:36' union all
select '02109','2012-3-1','17:36' union all
select '02103','2012-3-1','07:36' union all
select '02103','2012-3-1','17:36' union all
select '02109','2012-3-2','07:38' union all
select '02102','2012-3-2','07:36'
declare @str varchar(max)
set @str=''
select @str=@str+','+QUOTENAME([recdate],'')+'=case when [recdate]='+QUOTENAME([recdate],'''')+
' then [rectime] else null end' from tbl group by [recdate]
exec('select [workid]'+@str+' from tbl')
print @str
/*
workid 2012-03-01 2012-03-02
02109 07:36:00.0000000 NULL
02109 09:36:00.0000000 NULL
02109 17:36:00.0000000 NULL
02103 07:36:00.0000000 NULL
02103 17:36:00.0000000 NULL
02109 NULL 07:38:00.0000000
02102 NULL 07:36:00.0000000
*/
------解决方案--------------------