This question already has an answer here:
I have the below SQl Table which has the data generated randomly
Code Data
SL Payroll 22
SL Payroll 33
SL Payroll 43
.. .....
I want to transfer the data so the format becomes as shown below
Code Data1 Data2 Data3 ..
SL Payroll 22 33 43 ....
Someone suggested Pivot table to transform the data as below
SELECT Code,
[22] Data1,
[33] Data2,
[43] Data3
FROM
(
SELECT *
FROM T
) TBL
PIVOT
(
MAX(Data) FOR Data IN([22],[33],[43])
) PVT
but this assumes the data points are static like 22,33 but they are dynamically generated. Can someone please help me out.
Thanks
I would use conditional aggregate along with
row_number()
:If you have a know or maximum number of desired columns, you can do a simple PIVOT, otherwise, you would need to go DYNAMIC
Example
Returns
to do dynamic pivot I did it a long way back.
UPDATED: Made more close to your code and talble names.
This will work for however many columns you want for the PIVOT, doesnt matter if 1 or 20