Home > Database > Mysql Tutorial > How to Transpose Tables in SQL Using UNPIVOT and PIVOT?

How to Transpose Tables in SQL Using UNPIVOT and PIVOT?

Barbara Streisand
Release: 2025-01-14 21:06:44
Original
522 people have browsed it

How to Transpose Tables in SQL Using UNPIVOT and PIVOT?

SQL table transposition: application of UNPIVOT and PIVOT functions

Transposing a table in SQL can be achieved using a combination of UNPIVOT and PIVOT functions. The UNPIVOT function converts columns to rows, while the PIVOT function converts rows to columns.

UNPIVOT data

UNPIVOT function is used to convert multiple columns into a single column. In the example, columns A and B need to be expanded. The following query demonstrates this process:

<code class="language-sql">select day, col, value
from yourtable
unpivot
(
  value
  for col in (A, B)
) unpiv;</code>
Copy after login

This query will create a new table with three columns: day, col and value. The col column will contain the column name (A or B) and the value column will contain the corresponding value from the expanded column.

PIVOT data

PIVOT function is used to convert rows into columns. In this example, the day values ​​(Mon, Tue, Wed, Thu, Fri) need to be converted into columns:

<code class="language-sql">select *
from
(
  select day, col, value
  from yourtable
  unpivot
  (
    value
    for col in (A, B)
  ) unpiv
) src
pivot
(
  max(value)
  for day in (Mon, Tue, Wed, Thu, Fri)
) piv;</code>
Copy after login

The final query will produce the desired output:

<code>Value | Mon | Tue | Wed | Thu | Fri
-------|-----|-----|-----|-----|-----
A      | 1   | 3   | 5   | 7   | 9
B      | 2   | 4   | 6   | 8   | 0</code>
Copy after login

Apply solution to your query

To apply this solution to your specific query, you can modify it as follows:

<code class="language-sql">select *
from
(
  select LEFT(datename(dw,datetime),3) as DateWeek,
    col, 
    value
  from DataTable 
  cross apply 
  (
    values ('A', ACalls), ('B', BCalls)
  ) c (col, value)
) src
pivot
(
  sum(value)
  for dateweek in (Mon, Tue, Wed, Thu, Fri)
) piv;</code>
Copy after login

This query will transform the data in your DataTable into the desired format.

The above is the detailed content of How to Transpose Tables in SQL Using UNPIVOT and PIVOT?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template