1

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

2
  • 1
    You can use pivot..... Commented Nov 10, 2015 at 5:15
  • You need dynamic pivoting Commented Nov 10, 2015 at 5:18

2 Answers 2

1

See below mention links

Efficiently convert rows to columns in sql server

http://www.databasejournal.com/features/mssql/converting-rows-to-columns-pivot-and-columns-to-rows-unpivot-in-sql-server.html

Dynamic Pivot in Sql Server

If still not found search on google there are many much examples on various technical sites https://www.google.co.in/?gws_rd=ssl#q=Convert+Rows+Into+Columns+SQL+Server

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the links but none of it is helping me to get the column names dynamically , It just transposes the rows into column header ,
No problem .. first get schema inforamtion of query.. and using that information make sql string .. then using sp_execSql .. you can get your desired result ... If you using any programming language in backend then the process will less complex ..
thanx it worked , And from the links i was able to understand the flow of Pivot
0

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     

1 Comment

It will be dynamic columns

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.