create table tb(id int,事情 nvarchar(20),结果 nvarchar(20))
insert into tb select 1,'吃饭','吃完'
insert into tb select 2,'吃饭','吃完'
insert into tb select 1,'上班','准时到'
go
alter table tb add sid int identity(1,1)
goselect id,事情,结果,sid=(select count(*) from tb where id=a.id and sid<=a.sid) into #t from tb a--select * from #tDECLARE @SQL VARCHAR(8000)
SET @SQL='select distinct id '
SELECT @SQL= @SQL+',(select 事情 from #t where sid='''+cast(sid as nvarchar(10))
+''' and id=a.id) as 事情'
+cast(sid as nvarchar(10))
+',(select 结果 from #t where sid='''+cast(sid as nvarchar(10))
+''' and id=a.id) as 结果'
+cast(sid as nvarchar(10))
from
(select distinct sid from #t) bset @sql=@sql+' from #t a'
print @sql
exec(@sql)drop table tb,#t