Home >Database >Mysql Tutorial >How Can I Efficiently Transpose Columns and Rows in SQL?

How Can I Efficiently Transpose Columns and Rows in SQL?

Linda Hamilton
Linda HamiltonOriginal
2025-01-23 09:47:14690browse

How Can I Efficiently Transpose Columns and Rows in SQL?

SQL Column and Row Transposition: A Practical Guide

SQL often requires transposing data – converting table orientation from vertical (columns) to horizontal (rows) or the reverse. While the PIVOT command exists, it can be cumbersome. This guide explores simpler alternatives.

Method 1: UNION ALL, Aggregate, and CASE Statement

This approach uses UNION ALL to unpivot, then an aggregate function (here, SUM) and a CASE statement to repivot:

<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>

Method 2: Static UNPIVOT and PIVOT

Knowing the number of columns to transform allows for a static UNPIVOT and PIVOT solution:

<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>

Method 3: Dynamic Pivot for Variable Columns

When dealing with a dynamic number of columns and colors, dynamic SQL offers a solution:

<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>

These methods provide versatile approaches to data transposition in SQL, adapting to various data manipulation needs.

The above is the detailed content of How Can I Efficiently Transpose Columns and Rows in SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn