In uw geval moet u de kolommen Salary, NoticePeriod, CTC
ongedaan maken in rijen, dan 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;
De UNPIVOT
transformeert de kolommen Salary, NoticePeriod, CTC
in waarden:
Vervolgens draait de spil de salariswaarden voor elke veldwaarde en transformeert de namen in kolommen.
En je moet het natuurlijk dynamisch doen in plaats van een lijst met namen te schrijven zoals deze:
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);
Dit geeft je:
- Live demo (Dank aan @lad2025 ervoor)