In Ihrem Fall sollten Sie die Spalten Salary, NoticePeriod, CTC
unpivotieren in Zeilen, dann PIVOT
:
WITH Unpivoted
AS
(
SELECT Name, Fields, SalaryValue
FROM salaries AS s
UNPIVOT
(
SalaryValue
FOR Fields IN(Salary, NoticePeriod, CTC)
) AS u
)
SELECT Fields, jack,bruce
FROM Unpivoted AS u
PIVOT
(
MAX(SalaryValue)
FOR Name IN(Jack, Bruce)
) AS p;
Das UNPIVOT
transformiert die Spalten Salary, NoticePeriod, CTC
in Werte:
Dann dreht der Pivot die Gehaltswerte für jeden Feldwert und wandelt die Namen in Spalten um.
Und natürlich müssen Sie es dynamisch tun, anstatt eine Namensliste wie diese zu schreiben:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @colnames AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
SELECT @cols = STUFF((SELECT distinct ',' +
QUOTENAME(name)
FROM salaries
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT @query = 'WITH Unpivoted
AS
(
SELECT Name, Fields, SalaryValue
FROM salaries AS s
UNPIVOT
(
SalaryValue
FOR Fields IN(Salary, NoticePeriod, CTC)
) AS u
)
SELECT Fields, ' + @cols + '
FROM Unpivoted AS u
PIVOT
(
MAX(SalaryValue)
FOR Name IN(' + @cols + ')' +
') p';
execute(@query);
Das ergibt:
- Live-Demo (Danke an @lad2025 dafür)