Click here to Skip to main content
16,009,238 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have a table named T1 which has data in a column. I have to make that column data to a row data for other table. For example...

ID      Salary

1	 48
2	 80
3	 50
4	 70
5	 85


I have other table T2 with 5 columns A1 to A5. I have to insert the values from T1 to T2 like...

A1  A2  A3  A4  A5
48  80  50  70  85


Heard I can use UNPIVOT and PIVOT. But I am not able to get what I want.

Can anyone please giude me on this?


Thanks,
Vasini
Posted
Updated 14-Oct-11 8:18am
v3

Try this:
SQL
SELECT [1] AS A1, [2] ASD A2, [3] AS A3, [4] AS A4, [5] AS A5
FROM
(
    SELECT ID, Salary
    FROM SalaryTable
) AS SourceTable
PIVOT
(
    SUM(Salary)
    FOR ID IN ([1], [2], [3], [4], [5])
) AS PivotTable

This is my first attempt using PIVOT[^] so I hope it is correct.
 
Share this answer
 
There may well be a better way to do this - I'm only just starting to look at PIVOT - but this works:
SQL
SELECT * FROM T1
PIVOT(MAX(SALARY) FOR ID IN ([1],[2], [3], [4], [5])) p
The 'p' at the end is necessary (the pivot needs a name, even if you don't refer to it again) and the MAX is needed because PIVOT requires an aggregate function.
 
Share this answer
 
Hi,

Solution2 worked perfectly. Thank you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900