Home >Database >Mysql Tutorial >How Can I Efficiently Convert Columns to Rows in SQL Server?
In-Depth Guide to Column Conversion in SQL Server
When working with tables containing a large number of metric columns, converting these columns into rows can be very beneficial for analysis and reporting purposes. This transformation involves restructuring the data to create new tables with a different schema.
Problem Statement
Consider the following table schema:
<code>[ID] [EntityID] [Indicator1] [Indicator2] [Indicator3] ... [Indicator150]</code>
The goal is to convert these metric columns into rows, creating a new table with the following schema:
<code>[ID] [EntityId] [IndicatorName] [IndicatorValue]</code>
Solution using UNPIVOT
An elegant solution to accomplish this task is to utilize the UNPIVOT function. The syntax of UNPIVOT is as follows:
<code>UNPIVOT ([unpivot column] FOR [pivot column] IN ([pivot values]))</code>
In this example, the unpivot column represents the indicator value (for example, "Indicator1", "Indicator2", etc.), while the pivot column represents the column name itself. The following query illustrates how to use UNPIVOT:
<code>select id, entityId, indicatorname, indicatorvalue from yourtable unpivot ( indicatorvalue for indicatorname in (Indicator1, Indicator2, Indicator3) ) unpiv;</code>
By executing this query, the metric columns will be converted into rows and the metric names and values will populate the new columns.
Alternatives
Besides UNPIVOT, there are other ways to convert columns to rows:
The choice of solution depends on the specific needs and the version of SQL Server used.
The above is the detailed content of How Can I Efficiently Convert Columns to Rows in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!