views:

330

answers:

1

I need to convert Database rows into columns and show the result in Gridview. My DB is as follows:

ID  Hotel   cDate                   Price
-----------------------------------------------
1   Hotel1  12/22/2009 12:00:00 AM  15.0000
2   Hotel2  12/22/2009 12:00:00 AM  25.0000
3   Hotel3  12/22/2009 12:00:00 AM  60.0000
4   Hotel4  12/22/2009 12:00:00 AM  55.0000
.
.
.

I've to show the results as below:

cDate                    Hotel1 Hotel2 Hotel3 Hotel4
12/22/2009 12:00:00 PM    15     25     60     55
12/22/2009 12:00:00 AM    ..     ..     ..     ..
12/22/2009 12:00:00 AM   
12/22/2009 12:00:00 AM
+2  A: 

If you're using SQL Server 2005 then you can use the Pivot operator.

See this MSDN article.

Here's the SQL Server 2005 T-SQL to do what you want to do:

DECLARE @listCol VARCHAR(2000)
DECLARE @query VARCHAR(4000)
SELECT  @listCol = STUFF(( SELECT DISTINCT
                                '],[' + Hotel
                        FROM    dbo.tblHotels
                        ORDER BY '],[' + Hotel
                        FOR XML PATH('')
                                    ), 1, 2, '') + ']'

SET @query =
'SELECT * FROM
      (SELECT cDate,Hotel,price
            FROM dbo.tblHotels) p
PIVOT (SUM(price) FOR Hotel
IN ('+@listCol+')) AS pvt'

EXECUTE (@query)
Alison