Мое решение будет динамическим PIVOT:
DROP TABLE IF EXISTS #mytemptable
CREATE TABLE #mytemptable
(
S_ID int
,S_NAME varchar(20)
,MARK_NUMBER varchar(20)
,MARK_VALUE int
)
INSERT INTO #mytemptable VALUES
(1,'TEST ','MARK1',50),
(1,'TEST ','MARK2',60),
(1,'TEST ','MARK3',70),
(2,' TEST_!','MARK1',40),
(2,' TEST_!','MARK2',50),
(2,' TEST_!','MARK3',40)
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(MARK_NUMBER)
FROM (SELECT DISTINCT p.MARK_NUMBER FROM #mytemptable AS p) AS x;
SET @sql = N'
SELECT *
FROM
( select S_ID, S_NAME, MARK_VALUE, MARK_NUMBER from #mytemptable
) AS j
PIVOT
(
SUM(MARK_VALUE) FOR MARK_NUMBER IN ('
+ STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p;';
PRINT @sql;
EXEC sp_executesql @sql;
DROP TABLE IF EXISTS #mytemptable