问题:
您需要将一个包含多个列的 SQL 表格转置,例如:
<code>Day A B --------- Mon 1 2 Tue 3 4 Wed 5 6 Thu 7 8 Fri 9 0</code>
转置成以下格式:
<code>Value Mon Tue Wed Thu Fri -------------------------- A 1 3 5 7 9 B 2 4 6 8 0</code>
解决方案:
要转置包含多个列的表格,您可以结合使用 UNPIVOT 和 PIVOT 函数。
<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>
这将生成所需的转置表。
附加说明:
<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>
以上是如何转置具有多列的 SQL 表?的详细内容。更多信息请关注PHP中文网其他相关文章!