2013-10-31 136 views
1

目前,我正在運行SQL Server 2008,並試圖得到以下子查詢的數據:移調行基於ID列列

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

分爲基於ID列單行:

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

這可能嗎?提前致謝!

乾杯, 硅

+1

由於您使用的是SQL Server(Yay!),請查看[PIVOT](http://technet.microsoft.com/en-us/library/ms177410(v = sql.105).aspx)運算符( 2005+)。玩的開心! (任何不需要動態SQL或某些過程代碼的解決方案都將被限制爲必須在查詢中指定的* fixed set *輸出列。) – user2864740

回答

1

您可以使用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

+0

Hi Roman, 感謝您的建議。我目前收到「操作數數據類型ntext對於最大運算符無效」。只是澄清字段名稱和選擇列是文本而不是ID的。 –

+0

請參閱http://sqlfiddle.com/#!3/38f32/7 - 您可以將它轉換爲nvarchar(最大) –

+0

絕對傳說!將它作爲nvarchar在子目錄中排序。 –