SQL 将多列转置为行

Posted

技术标签:

【中文标题】SQL 将多列转置为行【英文标题】:SQL Transpose Multiple Columns to Rows 【发布时间】:2017-03-09 14:57:20 【问题描述】:

我有 Fig1 中的数据,需要将 Columns 转换为 Rows,如图 2 所示(必需的结果)。

这将是多年和多个时期

【问题讨论】:

做一个 UNION ALL,为每个描述类型选择一个。 你用的是什么sql平台? 【参考方案1】:

在任何平台上 UNION ALL 都可以工作。有些平台有 UNPIVOT,但你没有说你在用什么。

SELECT Division, Period, 'Total Cost' AS DESCRIPTION, TotalCost as Value
FROM A_TABLENAME_YOU_DID_NOT_SAY

UNION ALL

SELECT Division, Period, 'Discount' AS DESCRIPTION, DISCOUNT AS Value
FROM A_TABLENAME_YOU_DID_NOT_SAY

UNION ALL

SELECT Division, Period, 'Net Sales' AS Descripion, NETSALES AS Value
FROM A_TABLENAME_YOU_DID_NOT_SAY

UNION ALL

SELECT Division, Period, 'Net Returns' AS DESCRIPTION, NETRETURNS AS Value
FROM A_TABLENAME_YOU_DID_NOT_SAY

UNION ALL

SELECT Division, Period, 'Gross Sales' AS DESCRIPTION, GROSSSALES AS Value
FROM A_TABLENAME_YOU_DID_NOT_SAY

UNION ALL

SELECT Division, Period, 'Gross Returns' AS DESCRIPTION, GROs-s-rETURNS AS Value
FROM A_TABLENAME_YOU_DID_NOT_SAY

【讨论】:

谢谢!!创意表名给我留下了深刻的印象。 @LDD - [I_SAY].[DONT_MOCK_THE_TABLE_NAME]【参考方案2】:
select Division, Period, 'Total Cost' as Description, TotalCost as Value
from MyTable
union
select Division, Period, 'Discount' as Description, Discount as Value
from MyTable
union
select Division, Period, 'Net Sales' as Description, NetSales as Value
from MyTable
union
select Division, Period, 'Net Returns' as Description, NetReturns as Value
from MyTable
union
select Division, Period, 'Gross Sales' as Description, GrossSales as Value
from MyTable
union
select Division, Period, 'Gross Returns' as Description, GrossReturns as Value
from MyTable

您也可以将其包装在视图中,然后使用您需要的任何排序或过滤在视图上进行选择

【讨论】:

谢谢乔,就是搞不定,尝试了最复杂的代码。 @LDD - 太好了,很高兴你完成了。如果此问题已完成,请通过接受答案来结束此问题。 (顺便说一句...我先回答)

以上是关于SQL 将多列转置为行的主要内容,如果未能解决你的问题,请参考以下文章

Oracle SQL Developer:如何使用 PIVOT 函数将行转置为列

Postgres 表选择多列并将结果(列)动态转换为行 - 将列转置为行

将列转置为行 SQL Server

在 SQL 中将行转置为列标题

oracle sql 11G中如何将列转置为行

oracle pl sql中如何将列数据转置为行