首页 > 解决方案 > SQL Server:将列转换为另一个并将其值附加到单独的列

问题描述

给出以下表格格式(而不是视图),并带有示例

 Name  | MonthYear |      Type     | budget | actual | revenue_forecast
google |   Nov-20  | Gross Billing |   50   |   70   | 40

我想让它有两行,“revenue_forecast”成为一种类型,它的值显示在预算之下,就像这样

 Name  | MonthYear |      Type        | budget | actual 
google |   Nov-20  | Gross Billing    |   50   |   70   
google |   Nov-20  | revenue_forecast |   40   |   null   

任何想法如何做到这一点?在这种情况下,与 unpivot 逻辑有点挣扎

标签: sqlsql-serverunpivot

解决方案


您可以尝试使用VALUES表值构造函数进行反透视,但请仔细考虑列的数据类型:

SELECT t.Name, t.MonthYear, v.[Type], v.budget, v.actual
FROM YourTable t
CROSS APPLY (VALUES
   (t.[type], t.budget, t.actual),
   ('revenue_forecast', t.revenue_forecast, NULL)
) v ([type], budget, actual)

以下完整查询可用于测试:

declare @table Table
(
    Name varchar(50),
    MonthYear varchar(10),
    Type Varchar(50),
    budget int,
    actual int,
    revenue_forecast int
)
INSERT INTO @table (Name, MonthYear, Type, budget, actual, revenue_forecast)
Values('google', 'Nov-20','Gross Billing',50,70,40)

select * from @table

SELECT t.Name, t.MonthYear, v.[Type], v.budget, v.actual
FROM @table t
CROSS APPLY (VALUES
   (t.[type], t.budget, t.actual),
   ('revenue_forecast', t.revenue_forecast, NULL)
) v ([type], budget, actual)

推荐阅读