如何解决SQL Server:将列取消透视,然后将其值附加到单独的列
提供以下表格格式(而不是其视图),并带有示例示例
import pandas as pd
column_names = [
'CEO_FEM_CAS','CEO_FEM_FTCONT','CEO_FEM_FTPERM','CEO_FEM_PTCONT','CEO_FEM_PTPERM','CEO_MAL_CAS','CEO_MAL_FTCONT','CEO_MAL_FTPERM','CEO_MAL_PTCONT','CEO_MAL_PTPERM','KMP_FEM_CAS','KMP_FEM_FTCONT','KMP_FEM_FTPERM','KMP_FEM_PTCONT','KMP_FEM_PTPERM','KMP_MAL_CAS','KMP_MAL_FTCONT','KMP_MAL_FTPERM','KMP_MAL_PTCONT','KMP_MAL_PTPERM',]
first_part = []
second_part = []
third_part = []
for column_name in column_names:
split_column_name = column.split('_')
first_part.append(split_column_name[0])
second_part.append(split_column_name[1])
third_part.append(split_column_name[2])
df = pd.DataFrame(columns=[first_part,second_part,third_part])
我要使其具有两行,其中'revenue_forecast'成为一种类型,并且其值在预算范围内显示,就像这样
Name | MonthYear | Type | budget | actual | revenue_forecast
google | Nov-20 | Gross Billing | 50 | 70 | 40
有什么想法可以做到吗?在这种情况下,我们难以摆脱不可思议的逻辑
解决方法
您可以尝试使用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,actual,revenue_forecast)
Values('google','Nov-20','Gross Billing',50,70,40)
select * from @table
SELECT t.Name,v.actual
FROM @table t
CROSS APPLY (VALUES
(t.[type],actual)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。