在SQL Server查询中将行转换为列

时间:2014-02-10 22:18:51

标签: sql sql-server sql-server-2008 pivot

我对SQL查询得到5行,数据截图如下:

enter image description here

我需要编写SQL查询,将这些行转换为5个Cols。结果应该是这样的:

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

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分: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 ║
╚═══════════════════════════════╩══════════════════════════╩═════════════════════╩═════════════════════════╩═══════════════╝