我正在尝试转换此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