我從 SQL Server 中提取了大約 5000 行的資料,如下所示。我將其復制粘貼到 Excel 檔案中。

但我想將資料轉換為這種格式:

我應該在第一步(SQL Server 端)還是在 Excel 中完成這項作業?哪種解決方案更容易研究和學習?
如果你能舉個例子,我也會很高興。
謝謝。
uj5u.com熱心網友回復:
如果您有一個已知或最大數量的列,您可以PIVOT與row_number()
如果最大值未知,則需要動態 SQL
示例或
編輯 - 動態 SQL 和變數資料型別的更新
Declare @SQL varchar(max) = (
Select string_agg(concat('[',Col,N,']'),',') within group (order by N,Col)
From (values ('Column1-')
,('Column2-')
,('Column3-')
,('Column4-')
) A(Col)
Cross Join ( Select distinct N=row_number() over (partition by ID order by ID) From YourTable ) B
)
Set @SQL = '
Select *
From (Select A.ID
,B.*
from (Select *
,Grp = row_number() over (partition by ID order by ID)
From YourTable
) A
Cross Apply ( Select col = concat([Key],''-'',Grp)
,Val = value
From OpenJson((Select A.* For JSON Path,Without_Array_Wrapper ))
) B
) src
Pivot (max(Val) for Col in ( ' @SQL ' ) ) pvt '
Exec(@SQL)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453217.html
