sql - 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 逻辑有点挣扎
解决方案
您可以尝试使用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)
推荐阅读
- swift - AppleTv - CustomOverlayViewController 在时间码处强制弹出
- php - 带有修改的 php 模糊电子邮件地址
- prometheus - 将流入百分位函数转换为 promQL
- python - 如何删除 CSV 特定行。(如 user_name = Max)
- python - 在未排序的列表中查找值
- rust - 具有相同分隔符的并排宏重复
- javascript - 你应该如何在 JavaScript 中实例化一个对象?
- swiftui - 在 SwiftUI TextEditor 中禁用标点符号的自动替换
- azure - GitHub Azure-pipelines check failure (Build #20210302.1 failed)
- python - How to use Python to asynchronously receive the stream data returned by the api