将SQL从一列多个原始数据转换为多列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将SQL从一列多个原始数据转换为多列相关的知识,希望对你有一定的参考价值。

我正在尝试转换此sql表:

--------------
| Value       |
---------------
| first row   |
| second row  |
| third row   |
---------------

在这样的事情:

----------------------------------------------------
| Value       | 01       | 02          | 03        |
----------------------------------------------------
| first row   |first row | second row  | third row |
----------------------------------------------------

使用数据透视查询我无法恢复数据,是字符串

SELECT *
FROM 
(SELECT Value
FROM Desc_sin ) AS Source
PIVOT
(MAX(Value) FOR Value IN ([1],[2],[3],[4])) AS PVT;

要么

SELECT 'Value'
[0], [1], [2],[3]
FROM
(SELECT Value
    FROM [Desc_sin]) AS st
PIVOT
(
max(Value)
FOR Value IN ([0], [1], [2],[3])
) AS PivotTable;
答案

可以在最终选择中分配VALUE列

但是,如果没有正确的顺序,则没有ORD的GTD。你可能会注意到我们有ORDER BY(选择NULL)

Select Value=[01],*
 From  (
        Select Item=format(Row_Number() over(Order By (Select NULL)),'00')
              ,ItemValue = Value
         from  YourTable
       ) A
 Pivot (max(ItemValue) for Item in ([01],[02],[03])) P

返回

Value       01          02          03
first row   first row   second row  third row
另一答案

请尝试以下方法

IF OBJECT_ID('tempdb..#temp')IS NOT NULL
DROP TABLE #temp
;With CTe( Value)
AS
(
SELECT 'first row'  UNION ALL 
SELECT 'second row' UNION ALL  
SELECT 'third row'   
)
SELECT * INTO #temp FROM cte

DECLARE @Columns nvarchar(100)

;WITH CTE
AS
(
SELECT TOP 1 Value , STUFF((SELECT DISTINCT ', '+(Value)
                            FROM #temp FOR XML PATH ('')),1,1,'') AS Col
)
SELECT DISTINCT Value,
        SPlit.a.value('/S[1]','nvarchar(1000)') AS [01],
        SPlit.a.value('/S[2]','nvarchar(1000)') AS [02],
        SPlit.a.value('/S[3]','nvarchar(1000)') AS [03]
FROM
(
SELECT Value, CAST('<S>'+ REPLACE(Col,',','</S><S>')+'</S>' AS XML ) As String
FROM CTE 
)c
CROSS APPLY String.nodes('S') AS SPlit (a)

结果

Value           01           02             03
---------------------------------------------------
first row    first row1  second row2     third row3

以上是关于将SQL从一列多个原始数据转换为多列的主要内容,如果未能解决你的问题,请参考以下文章

MySQL关联表多行转多列?

SQL 如何把一列的值转换成一行显示

需要将字符串从一列分隔为多列,以';'分隔bigquery中的分隔符

Oracle SQL 数据透视表从一列变为两列

C#将查询返回的数据(一行多列)怎么转换成一列多行dataTable?

MS SQL Pivot 来自多列的长数据