Dalam kasus Anda, Anda harus menghapus kolom Salary, NoticePeriod, CTC
menjadi beberapa baris, lalu 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
akan mengubah kolom Salary, NoticePeriod, CTC
menjadi nilai:
Kemudian pivot akan memutar nilai gaji untuk setiap nilai bidang dan mengubah nama menjadi kolom.
Dan tentu saja Anda harus melakukannya secara dinamis daripada menulis daftar nama seperti ini:
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);
Ini akan memberi Anda:
- Demo Langsung (Terima kasih kepada @lad2025 untuk itu)