Home >Database >Mysql Tutorial >How to Easily Transpose Columns and Rows in SQL?
Easy way to convert SQL rows and columns
In SQL, it is a common requirement to convert row and column data to obtain a more practical data format. Although the PIVOT function looks complicated, there are actually simpler alternatives.
Use UNION ALL, aggregate functions and CASE statements
If you cannot use the PIVOT function, you can use a combination of UNION ALL, aggregate functions and CASE statements:
<code class="language-sql">select name, sum(case when color = 'Red' then value else 0 end) Red, sum(case when color = 'Green' then value else 0 end) Green, sum(case when color = 'Blue' then value else 0 end) Blue from ( select color, Paul value, 'Paul' name from yourTable union all select color, John value, 'John' name from yourTable union all select color, Tim value, 'Tim' name from yourTable union all select color, Eric value, 'Eric' name from yourTable ) src group by name</code>
Static UNPIVOT and PIVOT methods
If the column value to be converted is known, you can use the UNPIVOT and PIVOT functions:
<code class="language-sql">select name, [Red], [Green], [Blue] from ( select color, name, value from yourtable unpivot ( value for name in (Paul, John, Tim, Eric) ) unpiv ) src pivot ( sum(value) for color in ([Red], [Green], [Blue]) ) piv</code>
Dynamic PIVOT method
For an unknown number of columns and colors, dynamic SQL can be used:
<code class="language-sql">DECLARE @colsUnpivot AS NVARCHAR(MAX), @query AS NVARCHAR(MAX), @colsPivot as NVARCHAR(MAX) select @colsUnpivot = stuff((select ','+quotename(C.name) from sys.columns as C where C.object_id = object_id('yourtable') and C.name <> 'color' for xml path('')), 1, 1, '') select @colsPivot = STUFF((SELECT ',' + quotename(color) from yourtable t FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'select name, '+@colsPivot+' from ( select color, name, value from yourtable unpivot ( value for name in ('+@colsUnpivot+') ) unpiv ) src pivot ( sum(value) for color in ('+@colsPivot+') ) piv' exec(@query)</code>
The above is the detailed content of How to Easily Transpose Columns and Rows in SQL?. For more information, please follow other related articles on the PHP Chinese website!