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
1.0k views
in Technique[技术] by (71.8m points)

sql - Transpose rows to columns based on ID column

I'm currently running SQL Server 2008 and trying to get the following subquery data:

ID | Field Name | Field Selection
1  |  Rating 1  |      Good
1  |  Rating 2  |      Good
1  |  Rating 3  |      Bad
2  |  Rating 1  |      OK

Grouped into a single row based on the ID column:

ID | Rating 1 | Rating 2 | Rating 3
1  |    Good  |    Good  |   Bad
2  |     OK   |    NULL  |   NULL

Is this possible? Thanks in advance!

Cheers, Si

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

you can use SQL Server pivot clause for this:

select
    p.*
from Table1
pivot(
    max([Field Selection])
    for [Field Name] in ([Rating 1], [Rating 2], [Rating 3])
) as p

or you can pivot manually:

select
    ID,
    max(case when [Field Name] = 'Rating 1' then [Field Selection] end) as [Rating 1], 
    max(case when [Field Name] = 'Rating 2' then [Field Selection] end) as [Rating 2],
    max(case when [Field Name] = 'Rating 3' then [Field Selection] end) as [Rating 3]
from Table1
group by ID

sql fiddle demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...