2014-02-10 120 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 ║ 
╚═══════════════════════════════╩══════════════════════════╩═════════════════════╩═════════════════════════╩═══════════════╝