SQL 将多列转为行
SQL Transpose Multiple Columns to Rows
我有图 1 中的数据,需要将列转置为图 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
您也可以将其包装在一个视图中,然后根据您需要的任何排序或过滤对视图执行 select
在任何平台上 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, GROSSRETURNS AS Value
FROM A_TABLENAME_YOU_DID_NOT_SAY
我有图 1 中的数据,需要将列转置为图 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
您也可以将其包装在一个视图中,然后根据您需要的任何排序或过滤对视图执行 select
在任何平台上 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, GROSSRETURNS AS Value
FROM A_TABLENAME_YOU_DID_NOT_SAY