Click here to Skip to main content
15,559,455 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need a query in sq l server which converts rows into columns dynamically..


please provide a solution
Posted

This operation is called matrix transposition in algebra. Since you specified only SQL-Server in the tags, I looked on google T-SQL solutions, but there are many approaches:
- Generic approach: http://www.extensionmethod.net/Details.aspx?ID=152[^]
- ASP.NET sample: Transpose a DataTable using C#[^], http://codemaverick.blogspot.hu/2008/02/transpose-datagrid-or-gridview-by.html[^]
- T-SQL: http://sqlandme.com/2011/04/20/tsql-transpose-data-using-using-pivot-and-unpivot/[^]
 
Share this answer
 
Comments
[no name] 17-Sep-12 3:27am    
thanks u
Hi,

You can achieve this by using Pivot. See the below example. You might be get the idea.

http://www.simple-talk.com/blogs/2007/09/14/pivots-with-dynamic-columns-in-sql-server-2005/[^]

Thanks,
Viprat
 
Share this answer
 
after lots of querying i got query that i want this query displays the output in cross tab format dynamically

consider i have table named SalesRepor having fields Month,Branch,Sales

SQL
declare @columns varchar(max)
declare @convert varchar(max)
select   @columns = stuff (( select distinct'],[' +  Month
                    from SalesReport
                  
                    for xml path('')), 1, 2, '') + ']'


set @convert =
'select * from (select Month,Branch,Sales from SalesReport) SalesRpt
    pivot(sum(Sales) for Month
    in ('+@columns+')) as pivottable'


execute (@convert)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900