-2

I have a table- EmployeeDetails. In which we have two columns :- ColumnName and Details. Below is the table:-

ColumnNames     Details
-----------     -------
Sno             1
Firstname       Daya
Lastname        Sharma
EmailId         <email1>@gmail.com
sno             2
Firstname       Kriti 
Lastname        joshi
EmailId         <email2>@yahoo.com

Now I need to convert firstname, lastname, emailed and sno in columns. How we can do this?

And I want to convert into Column Name as

Sno  FirstName  Lastname  Emailid
1    Daya       Sharma    <email1>@gmail.com
2    Kriti      Joshi     <email2>@yahoo.com
Taryn
  • 242,637
  • 56
  • 362
  • 405

3 Answers3

0
select sno,firstname,lastname,Emailid
from
(
select columnnames,details from table
)d

pivot
(
max(details)
for columnnames in([sno],[firstname],[lastname],[emailid])
)piv;
vhadalgi
  • 7,027
  • 6
  • 38
  • 67
0

You may refer below link for the answer. Same question has been posted at below link :

Efficiently convert rows to columns in sql server

Community
  • 1
  • 1
SpiderCode
  • 10,062
  • 2
  • 22
  • 42
0

You have to have at least one more column (let's call it EmployeeID) to be able to properly pivot your data. Otherwise there is no way to tell which last name belongs to which first name, Son, emailid etc

If you were to have such a column then PIVOT would work as expected

SELECT Sno, Firstname, Lastname, Emailid
  FROM
(
  SELECT EmployeeId, ColumnNames, Details 
    FROM EmployeeDetails
) s
PIVOT
(
  MAX(Details)
  FOR ColumnNames IN([Sno],[Firstname],[Lastname],[Emailid])
) p;

Output:

| SNO | FIRSTNAME | LASTNAME |            EMAILID |
|-----|-----------|----------|--------------------|
|   1 |      Daya |   Sharma | @gmail.com |
|   2 |     Kriti |    joshi | @yahoo.com |

Here is SQLFiddle demo

peterm
  • 91,357
  • 15
  • 148
  • 157