SQL 服务器:将列逆透视到另一个列并将其值附加到单独的列
SQL server: unpivot column into another and append its value to separate column
使用以下 table 格式(而不是视图),以及示例
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
知道如何做到这一点吗?对于这种情况
,在反透视逻辑上有点挣扎
您可以尝试使用 VALUES
table 值构造函数进行逆透视,但请仔细考虑列的数据类型:
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)
使用以下 table 格式(而不是视图),以及示例
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
知道如何做到这一点吗?对于这种情况
,在反透视逻辑上有点挣扎您可以尝试使用 VALUES
table 值构造函数进行逆透视,但请仔细考虑列的数据类型:
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)