首頁 >資料庫 >mysql教程 >如何有效率地將SQL Server表列轉換為行?

如何有效率地將SQL Server表列轉換為行?

Linda Hamilton
Linda Hamilton原創
2025-01-21 19:17:13282瀏覽

How to Efficiently Convert SQL Server Table Columns into Rows?

將SQL Server表列轉換為行

將表格列轉換為行是一種非常有用的資料處理技巧。本文介紹了幾種在SQL Server中完成此任務的方法。

UNPIVOT函數

UNPIVOT函數明確地將列轉換為行,從而實現靈活的資料重組。例如,要轉換範例表模式中'Indicator1'到'Indicator150'列:

<code class="language-sql">select id, entityId,
  indicatorname,
  indicatorvalue
from yourtable
unpivot
(
  indicatorvalue
  for indicatorname in (Indicator1, Indicator2, Indicator3)
) unpiv;</code>

使用CROSS APPLY和UNION ALL

或者,可以使用CROSS APPLY和UNION ALL組合多個子查詢:

<code class="language-sql">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);</code>

使用CROSS APPLY和VALUES子句

在支援的SQL Server版本中,可以使用CROSS APPLY和VALUES子句:

<code class="language-sql">select id, entityid,
  indicatorname,
  indicatorvalue
from yourtable
cross apply
(
  values
  ('Indicator1', Indicator1),
  ('Indicator2', Indicator2),
  ('Indicator3', Indicator3),
  ('Indicator4', Indicator4)
) c (indicatorname, indicatorvalue);</code>

針對大量欄位的動態SQL

對於需要解旋的大量列的表,請考慮使用動態SQL以程式設計方式產生查詢:

<code class="language-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('')), 1, 1, '')

set @query 
  = 'select id, entityId,
        indicatorname,
        indicatorvalue
     from yourtable
     unpivot
     (
        indicatorvalue
        for indicatorname in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;</code>

以上是如何有效率地將SQL Server表列轉換為行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn