2

現在、SQL Server 2008 を実行しており、次のサブクエリ データを取得しようとしています。

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

ID 列に基づいて 1 つの行にグループ化されます。

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

これは可能ですか?前もって感謝します!

乾杯、Si

4

1 に答える 1

3

これには SQL Server のピボット句を使用できます。

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

または手動でピボットすることもできます:

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

于 2013-10-31T18:54:24.690 に答える