Пожалуйста, отметьте это
Declare @yt TABLE( [PRN] bigint, studentName varchar(500), moduleName varchar(500),theoryMarks varchar(500) );
INSERT INTO @yt ( [PRN], studentName, moduleName, theoryMarks )
VALUES (180841220008, 'Mahendra','A', 12),
(180841220009, 'Mahendra1','A', 13),
(180841220008, 'Mahendra','B', 12),
(180841220009, 'Mahendra1','B', 13)
select [PRN], studentName, moduleName, theoryMarks from @yt
select [PRN], studentName, [A] [moduleName A],[B] [moduleName B]from ( select [PRN], studentName, moduleName, theoryMarks from @yt ) src
pivot
(
max(theoryMarks)
for
moduleName in ([A], [B])
) piv;
Вывод будет:
Если вам нужен динамический c запрос для результат, проверьте это с помощью «For XML Path»
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=ef97e15e48b531dfae538c6bcdf813eb https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=1578790046398e64f5ac7ea091d324a5
create table temp( [PRN] bigint, studentName varchar(500), moduleName varchar(500),theoryMarks varchar(500) );
INSERT INTO temp ( [PRN], studentName, moduleName, theoryMarks )
VALUES (180841220008, 'Mahendra','A', 12),
(180841220009, 'Mahendra1','A', 13),
(180841220008, 'Mahendra','B', 12),
(180841220009, 'Mahendra1','B', 13)
select [PRN], studentName, moduleName, theoryMarks from temp
-----
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.moduleName)
FROM temp c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT [PRN], studentName, ' + @cols + ' from
(
select [PRN], studentName, moduleName, theoryMarks
from temp
) x
pivot
(
max(theoryMarks)
for moduleName in (' + @cols + ')
) p'
execute(@query)