在SQL Server查询中将行转换为列
我在一个SQL查询中得到了5行,数据截图如下所示: 我需要编写SQL查询,将这些行转换为5列。结果应该是这样的:在SQL Server查询中将行转换为列,sql,sql-server,sql-server-2008,pivot,Sql,Sql Server,Sql Server 2008,Pivot,我在一个SQL查询中得到了5行,数据截图如下所示: 我需要编写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 任何帮助都将不胜感激。谢谢 测试数据 质疑 结果集
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
任何帮助都将不胜感激。谢谢 测试数据
质疑
结果集
查找PIVOT并在你遇到Stuck的地方发布此问题似乎与主题无关,因为OP正在寻找有关如何解决其问题的资源。我没有得到任何答案框来回答此问题,而不是PIVOT,我们还可以使用max和Case条件;将CTE设置为Select LEFT trm_desc,CHARDINDEX':',trm_desc-1As Col,RIGHTRM_desc,LENtrm_desc-CHARDINDEX':',trm_desc-1As Val,行号按trm_desc AS RN从@Table选择MAXSCASE当RN=1时,Val以“Select”结束,当RN=2时,Val以“其他”结束,当RN=3时,Val以“付款”结束,当RN=4时,MAXCASE值以“供应”结束;当RN=5时,MAXCASE值以“税收”结束
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 ║
╚═══════════════════════════════╩══════════════════════════╩═════════════════════╩═════════════════════════╩═══════════════╝