Попробуйте:
CREATE TABLE #yt
(
[Id] INT
,[FKId] INT
,[TypeId] TINYINT
,[Score] INT
,[ScoreDate] DATE
)
INSERT INTO #yt
VALUES (1, 317, 1, 90, '2019-01-01')
,(2, 317, 1, 80, '2019-01-02')
,(3, 317, 2, 65, '2019-01-03')
,(4, 317, 2, 80, '2019-01-04')
,(5, 318, 1, 82, '2019-01-01')
,(6, 318, 1, 78, '2019-01-02')
,(7, 318, 2, 55, '2019-01-03')
,(8, 318, 2, 63, '2019-01-04');
select *
from
(
SELECT [FKId]
,CHAR(64 + DENSE_RANK() OVER (PARTITION BY FKID ORDER BY TypeID)) + CAST(DENSE_RANK() OVER (PARTITION BY FKID, TypeID ORDER BY [ScoreDate]) AS VARCHAR(12))
,[Score]
FROM #yt
) src ([FKId], [TypeID], [Score])
pivot
(
max([Score])
for [TypeId] in ([A1], [A2], [B1], [B2])
) piv;
DROP TABLE #yt;
или, если хотите, чтобы оно было динамичным:
DECLARE @DynamicTSQLStatement NVARCHAR(MAX)
,@DynamicColumns NVARCHAR(MAX)
SET @DynamicColumns = STUFF
(
(
SELECT DISTINCT ',[' + CHAR(64 + DENSE_RANK() OVER (PARTITION BY FKID ORDER BY TypeID)) + CAST(DENSE_RANK() OVER (PARTITION BY FKID, TypeID ORDER BY [ScoreDate]) AS VARCHAR(12)) + ']'
FROM #yt
FOR XML PATH('') ,TYPE
).value('.', 'NVARCHAR(MAX)')
,1
,1
,''
);
SET @DynamicTSQLStatement = N'
select *
from
(
SELECT [FKId]
,CHAR(64 + DENSE_RANK() OVER (PARTITION BY FKID ORDER BY TypeID)) + CAST(DENSE_RANK() OVER (PARTITION BY FKID, TypeID ORDER BY [ScoreDate]) AS VARCHAR(12))
,[Score]
FROM #yt
) src ([FKId], [TypeID], [Score])
pivot
(
max([Score])
for [TypeId] in ('+@DynamicColumns+')
) piv;'
EXEC sp_executesql @DynamicTSQLStatement;