SQL面接試験問題の行列転換


行列の変換  張学生の成績表(CJ)があると仮定して、次のようにName Subject Result張三国語80枚の三数学90枚の三物理85李四数学92李四物理82  姓名の国語の数学の物理の張三80 90李四85 92 82になりたいです。 
declare @sql varchar(4000)
set @sql = 'select Name'
select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']'
from (select distinct Subject from CJ) as a
select @sql = @sql+' from test group by name'
exec(@sql)
 
行列の変換→結合  表Aがあります。id pid 1 1 1 2 2 2 1 2 2 3 1はどうやって表B:id pid 1,2,3 2,2 3 3 1,2 3 1  結合の関数を作成します。
create function fmerg(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str=''
select @str=@str+','+cast(pid as varchar) from  A where id=@id
set @str=right(@str,len(@str)-1)
return(@str)
End
go