Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

sql server - Convert Database Rows into Columns

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  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...