Display data horizontally using UNPIVOT in SQL Server

Last Reply 3 months ago By pandeyism

Posted 3 months ago

I want my selected data records as a horizontal.

for example

if my selected data is,

select id, name, address from  table then I got it as

id  name  address

1    abc    Pune

but I want it as a

id 1

name abc 

address pune

please reply.

thank u.

You are viewing reply posted by: pandeyism 3 months ago.
Posted 3 months ago

Hi abc,

Refer below sample query.

SQL

CREATE TABLE #TestCustomers(Id VARCHAR(20), Name VARCHAR(20), [Address] VARCHAR(20))
INSERT INTO #TestCustomers VALUES(1,'abc','Pune')

SELECT DISTINCT [Column A] ,[Column B]
FROM
   (SELECT [Id],[Name],[Address]
   FROM #TestCustomers) p
UNPIVOT
   ([Column B] FOR [Column A] IN
      ([Id],[Name],[Address])
)AS unpvt;
DROP TABLE #TestCustomers

Output

Column A Column B
Address Pune
Id 1
Name abc