Akhil R J
Akhil R J

Reputation: 184

Convert Rows Into Columns SQL Server

I want to convert my output which is like

BachNo|Release Qty 
----------
A     |10
A     |30
A     |40
B     |90
B     |30

I want to transpose this structure into

BatchNO | Qty Release1 | Qty Release2 | Qty Release3
----------------------------------------------------
A       |     10       |    30        |   40
B       |     90       |    30        |  Null

The number of rows generated in the 1st output will be dynamic, so the transposed output can have n number of columns

Upvotes: 1

Views: 199

Answers (2)

Maddy
Maddy

Reputation: 123

For known number of columns its possible, but for dynamic number of columns am not very sure. Although you can use something like this and further split it later while processing.

SELECT BatchNo , STUFF(( SELECT  ','+ ReleaseQty FROM TableName a
WHERE b.BatchNo = a.BatchNo FOR XML PATH('')),1 ,1, '')  Members
FROM TableName b
GROUP BY BatchNo;

This should give you an output of something like :

BatchNo  | ReleaseQty
-------- | ------------------------
A        |  10,30,40
B        |  90,30     

Upvotes: 0

Related Questions