如何在 SQL Server (T-SQL) 中將列轉換為行?
Jan 21, 2025 pm 07:22 PMSQL Server 中將列轉換為行的幾種方法
本文介紹如何將 SQL Server 表中的列資料轉換為行資料。假設你的表格結構如下:
[ID] [EntityID] [Indicator1] [Indicator2] [Indicator3] ... [Indicator150]
登入後複製
目標是將資料轉換為以下結構:
[ID] [EntityId] [IndicatorName] [IndicatorValue]
登入後複製
目標結果範例:
<code>1 1 'Indicator1' 'Indicator 1 的值' 2 1 'Indicator2' 'Indicator 2 的值' 3 1 'Indicator3' 'Indicator 3 的值' 4 2 'Indicator1' 'Indicator 1 的值'</code>
登入後複製
解:
以下幾種方法可以實現列到行的轉換:
1. 使用 UNPIVOT 函數
UNPIVOT 函數可以有效地將列轉換為行:
SELECT id, entityId, indicatorname, indicatorvalue FROM yourtable UNPIVOT ( indicatorvalue FOR indicatorname IN (Indicator1, Indicator2, Indicator3) ) unpiv;
登入後複製
請確保參與轉換的欄位的資料類型一致。
2. 使用 CROSS APPLY 和 UNION ALL
另一種方法是使用 CROSS APPLY 和 UNION ALL:
SELECT id, entityid, indicatorname, indicatorvalue FROM yourtable CROSS APPLY ( SELECT 'Indicator1', Indicator1 UNION ALL SELECT 'Indicator2', Indicator2 UNION ALL SELECT 'Indicator3', Indicator3 UNION ALL SELECT 'Indicator4', Indicator4 ) c (indicatorname, indicatorvalue);
登入後複製
3. 使用 CROSS APPLY 和 VALUES (適用於較新版本的 SQL Server)
在較新的 SQL Server 版本中,可以使用 CROSS APPLY 和 VALUES 子句:
SELECT id, entityid, indicatorname, indicatorvalue FROM yourtable CROSS APPLY ( VALUES ('Indicator1', Indicator1), ('Indicator2', Indicator2), ('Indicator3', Indicator3), ('Indicator4', Indicator4) ) c (indicatorname, indicatorvalue);
登入後複製
4. 使用動態 SQL (適用於大量 Indicator 欄位)
對於包含大量 Indicator 欄位的大型資料表,可以使用動態 SQL 自動產生查詢:
DECLARE @colsUnpivot AS NVARCHAR(MAX), @query AS NVARCHAR(MAX); SELECT @colsUnpivot = STUFF((SELECT ',' + QUOTENAME(C.column_name) FROM information_schema.columns AS C WHERE C.table_name = 'yourtable' AND C.column_name LIKE 'Indicator%' FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ''); SET @query = 'SELECT id, entityId, indicatorname, indicatorvalue FROM yourtable UNPIVOT ( indicatorvalue FOR indicatorname IN (' + @colsUnpivot + ') ) u'; EXEC sp_executesql @query;
登入後複製
選擇哪一種方法取決於你的表的大小和 SQL Server 版本。 對於較少的列,前三種方法足夠;而對於包含大量 Indicator
列的表,動態 SQL 方法更有效率。 記得將 yourtable
替換成你的實際表名。
以上是如何在 SQL Server (T-SQL) 中將列轉換為行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

在 Linux 中運行 MySQl(有/沒有帶有 phpmyadmin 的 podman 容器)
