Click here to Skip to main content
15,896,348 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to make a table result for below in sql server?.


Column Col1 Col2 Col3 Col4 Col5
A 6.05 7.15 9.5 8.5 6.5


Column Values
Col1 6.05
Col2 7.15
Col3 9.5
Col4 8.5
Col5 6.5

What I have tried:

I'm trying to this type but, i'm getting in values column 1,1,1,1. Can you please any one response. this is urgent.
Posted
Updated 26-Mar-18 0:56am

1 solution

Try reading this:
Simple Way To Use Pivot In SQL Query[^]
By the way it is only urgent to you, not us and it's a lot easier to help people who post the code they are having a problem with

[EDIT]

It is not clear from your question whether you are trying to transform from a single row to many or from many rows to a single row. This is why I asked to see your query as it would have helped me to understand your question better.

However, here are some simple examples that you could use to fix your problem...

1. You have a table with many rows and you want a single row from it.
SQL
CREATE TABLE #demo1 ( c varchar(10), f float )

insert into #demo1 (c,f) values
('Col1' ,6.05),('Col2' ,7.15), 
('Col3' ,9.5 ),('Col4' ,8.5 ),('Col5' ,6.5)
Use PIVOT...
SQL
SELECT * FROM 
(SELECT c, f FROM #demo1) as s
PIVOT (MAX(f) FOR c IN (Col1,Col2,Col3,Col4,Col5)) AS p
Results:
6.05	7.15	9.5	8.5	6.5
2. You have a table with a single row and you want multiple rows from it.
SQL
CREATE TABLE #demo2
(
	letter varchar(1),
	Col1 float,
	Col2 float, 
	Col3 float,
	Col4 float,
	Col5 float
)
insert into #demo2 (letter, Col1,Col2,Col3,Col4,Col5) values
('A',6.05, 7.15, 9.5, 8.5, 6.5)
There are two methods you can use

a) "Brute force"
SQL
SELECT 'Col1' AS [Column], Col1 FROM #demo2
UNION
SELECT 'Col2' AS [Column], Col2 FROM #demo2
UNION
SELECT 'Col3' AS [Column], Col3 FROM #demo2
UNION
SELECT 'Col4' AS [Column], Col4 FROM #demo2
UNION
SELECT 'Col5' AS [Column], Col5 FROM #demo2
ORDER BY [Column]
or b) UNPIVOT
SQL
SELECT c, f FROM
(SELECT Col1,Col2,Col3,Col4,Col5 FROM #demo2 ) s
UNPIVOT
(f FOR c IN (Col1,Col2,Col3,Col4,Col5)) AS upvt
ORDER BY c
Both give the same result
Col1	6.05
Col2	7.15
Col3	9.5
Col4	8.5
Col5	6.5
 
Share this answer
 
v2
Comments
IsaiSelvan 26-Mar-18 6:49am    
I'm trying to this way but i'm getting error. Can you please provide a query for above mention table format
CHill60 26-Mar-18 6:55am    
As I said ... " it's a lot easier to help people who post the code they are having a problem with". Share the code you are having a problem with and we will hopefully be able to find the problem for you
IsaiSelvan 26-Mar-18 6:56am    
ok thanks. I'll try

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