将数据库行转换为列

时间:2009-12-22 12:55:55

标签: sql-server pivot rows

我需要将数据库行转换为列并在Gridview中显示结果。我的数据库如下:

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
.
.
.

我要将结果显示如下:

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  

1 个答案:

答案 0 :(得分:2)

如果您使用的是SQL Server 2005,则可以使用Pivot运算符。

See this MSDN article

这是SQL Server 2005 T-SQL做你想做的事情:

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)