Código SQL:
Ver originalDECLARE @SQL VARCHAR(MAX);
WITH T AS
(SELECT ROW_NUMBER() OVER(Partition BY rut ORDER BY fono) Nm,
*
FROM #temp),
Numeros AS
(SELECT DISTINCT Nm
FROM T)
SELECT @SQL=IsNull(@SQL+','+CHAR(13),'')+' Max(Case When Nm='+CAST(Nm AS VARCHAR)+' Then fono End) ['+CAST(Nm AS VARCHAR)+']'
FROM Numeros;
SELECT @SQL=
'With T As
(Select Row_Number() Over(Partition By rut Order By fono) Nm,
*
From #temp)
Select rut,'+CHAR(13)+
+@SQL+CHAR(13)+
'From T
Group By rut
Order By rut;'
Print @SQL;
EXEC(@SQL);
SELECT CAST(0x460065006C0069007A0020006100F1006F0020006E007500650076006F00 AS NVarchar);