试试这个 :
begin try
create table #test
(Entity_ID int,Certificate_ID int,CertificateExpiry date)
insert into #test values(1,1,'01/01/2013')
insert into #test values(1,2,'05/01/2013')
insert into #test values(1,5,'01/05/2013')
insert into #test values(1,9,'05/12/2013')
insert into #test values(2,1,'10/05/2013')
insert into #test values(2,2,'12/03/2013')
insert into #test values(4,6,'2/05/2013')
insert into #test values(5,8,'4/09/2013')
--select * from #test
DECLARE @Certificate_Ids VARCHAR(8000)
SELECT @Certificate_Ids = COALESCE(@Certificate_Ids + '], [', '') + cast(Certificate_ID as varchar(20)) FROM
(select distinct Certificate_ID from #test ) as a
Set @Certificate_Ids='['+@Certificate_Ids+']'
--print @Certificate_Ids
Declare @query varchar(max)
Set @query=
'SELECT
Entity_ID, ' + @Certificate_Ids + '
FROM #test
PIVOT
(
MAX(CertificateExpiry)
FOR Certificate_ID in (' + @Certificate_Ids + ' )
) A'
print @query
exec(@query)
drop table #test
end try
begin catch
drop table #test
end catch