12,548,514 members (54,569 online)
Rate this:
See more:
I need a query in sq l server which converts rows into columns dynamically..

Posted 14-Sep-12 23:08pm

Rate this:

## Solution 1

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/[^]

thanks u
Rate this:

## Solution 2

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
Rate this:

## Solution 3

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)
```

Top Experts
Last 24hrsThis month
 Suvendu Shekhar Giri 145 OriginalGriff 105 Dave Kreskowiak 100 ppolymorphe 100 Rbabs 75
 OriginalGriff 3,892 Suvendu Shekhar Giri 1,713 John Simmons / outlaw programmer 1,687 ppolymorphe 1,541 Karthik Bangalore 1,210

Web01 | 2.8.161021.1 | Last Updated 10 Jun 2016