Click here to Skip to main content
15,605,787 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

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

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

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

Share this answer
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:[^]
- ASP.NET sample: Transpose a DataTable using C#[^],[^]
- T-SQL:[^]
Share this answer
[no name] 17-Sep-12 3:27am    
thanks u

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