Home >Database >Mysql Tutorial >How to Transpose a SQL Table with Multiple Columns?
Question:
You need to transpose a SQL table with multiple columns, for example:
<code>Day A B --------- Mon 1 2 Tue 3 4 Wed 5 6 Thu 7 8 Fri 9 0</code>
Transpose to the following format:
<code>Value Mon Tue Wed Thu Fri -------------------------- A 1 3 5 7 9 B 2 4 6 8 0</code>
Solution:
To transpose a table with multiple columns, you can use the UNPIVOT and PIVOT functions together.
<code class="language-sql">select day, col, value from yourtable unpivot ( value for col in (A, B) ) unpiv</code>
<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>
This will generate the required transposed table.
Additional notes:
<code class="language-sql">select * from ( select day, col, value from yourtable cross apply ( values ('A', ACalls), ('B', BCalls) ) c (col, value) ) src pivot ( max(value) for day in (Mon, Tue, Wed, Thu, Fri) ) piv</code>
<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>
The above is the detailed content of How to Transpose a SQL Table with Multiple Columns?. For more information, please follow other related articles on the PHP Chinese website!