Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server, how can I transpose data of a column [duplicate]

Possible Duplicate:
Concatenate many rows into a single text string?

I have a query

SELECT city FROM cityTable

it returns

delhi
faridabad
haryana
mathura
kerla

I just want result in transpose manner something like

delhi | faridabad | haryana | mathura | kera

How is it possible?

like image 790
RAKESH HOLKAR Avatar asked May 24 '12 07:05

RAKESH HOLKAR


3 Answers

SELECT STUFF (
 (SELECT N', ' + city FROM CityTable FOR XML PATH(''),TYPE)
  .value('text()[1]','nvarchar(max)'),1,2,N'')

Concatenate many rows into a single text string?

like image 116
Darren Avatar answered Oct 08 '22 22:10

Darren


declare @city nvarchar(max)
SELECT @city = coalesce(@city+' | ', '')+city FROM cityTable 

EDIT:

In order to show the result

SELECT @city
like image 31
t-clausen.dk Avatar answered Oct 08 '22 22:10

t-clausen.dk


You can use the PIVOT and UNPIVOT as the example posted on here

TSQL – Transpose Data using Using PIVOT and UNPIVOT

NOTE: You can find the syntax on BOL (books on line) of SQL

like image 40
Luka Milani Avatar answered Oct 09 '22 00:10

Luka Milani