2014-02-10 173 views
-1

我正在對一個SQL查詢5行,數據截圖如下:轉換行到列在SQL Server查詢

enter image description here

我需要編寫SQL查詢,將這些行轉換爲5列數。結果應該是這樣的:

Col1 ---> Value of First Row 

Col2 ---> Value of Second Row 

Col3 ---> Value of Third Row 

Col4 ---> Value of Fourth Row 

Col5 ---> Value of Fifth Row 

任何幫助,將不勝感激。謝謝!

+0

[這裏有一個很好的資源,讓您開始。(HTTP://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx) – Kermit

+0

擡頭看看PIVOT併發帖讓你陷入困境 – Randy

+2

這個問題看起來是題外話題,因爲OP正在尋找資源如何解決他們的問題。 – Kermit

回答

1

測試數據

DECLARE @Table TABLE(trm_desc VARCHAR(300)) 
INSERT INTO @Table VALUES 
('Supply: All goods supplied bla bla...'), 
('Payment: to be made 10 April 2013'), 
('Delivery: Today 07 March 2013'), 
('Taxes: The price is bla bla...'), 
('Others: other bla bla') 

查詢

SELECT * FROM 
(
SELECT LEFT(trm_desc, CHARINDEX(':', trm_desc)-1) AS Cols 
     ,RIGHT(trm_desc, LEN(trm_desc)-CHARINDEX(':', trm_desc)-1) Value 
FROM @Table) Q 
PIVOT (MAX(Value) 
     FOR Cols 
     IN ([Supply],[Payment],[Delivery],[Taxes],[Others]) 
     )p 

結果集

╔═══════════════════════════════╦══════════════════════════╦═════════════════════╦═════════════════════════╦═══════════════╗ 
║   Supply    ║   Payment   ║  Delivery  ║   Taxes   ║ Others  ║ 
╠═══════════════════════════════╬══════════════════════════╬═════════════════════╬═════════════════════════╬═══════════════╣ 
║ All goods supplied bla bla... ║ to be made 10 April 2013 ║ Today 07 March 2013 ║ The price is bla bla... ║ other bla bla ║ 
╚═══════════════════════════════╩══════════════════════════╩═════════════════════╩═════════════════════════╩═══════════════╝