I dit tilfælde bør du fjerne pivoteringen af kolonnerne Salary, NoticePeriod, CTC
i rækker og derefter 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;
UNPIVOT
vil transformere kolonnerne Salary, NoticePeriod, CTC
til værdier:
Derefter vil pivoten pivotere lønværdierne for hver feltværdi og omdanne navnene til kolonner.
Og selvfølgelig skal du gøre det dynamisk i stedet for at skrive en liste med navne som denne:
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);
Dette vil give dig:
- Live-demo (Tak til @lad2025 for det)