如何在SQL中取消透视?(SAP HANA)(从列到行)
我需要取消一些SAP HANA中的数据.我设置了一个示例表来对其进行尝试,但仍然无处可做.
I need to unpivot some data in SAP HANA. I set up an example table to try it out on, but I still can't get anywhere.
实际的表包含1000的ID和〜50列,但是我想对许多表执行此操作,因此尽管我可以指定FieldNames(原始列),但最好有一个自动化的解决方案.
The actual table contains 1000's of ID's and ~50 columns, but I want to do this for many tables, so while I can specify the FieldNames(Original Columns), it would be nice to have an automated solution.
这是我设置的示例表:
我想将结果转换成这种形式:
I would like to get the results into this form:
注意:?"代表NULL.
Note: The '?' represents NULL.
要创建示例表,请执行以下操作:
To create the example table:
create local temporary table #example
(
ID NVARCHAR(255),
Name NVARCHAR(255),
Country NVARCHAR(255),
Balance Decimal(18,2)
);
insert into #example values('ID1','Bill','USA', 100);
insert into #example values('ID2','','', 45);
insert into #example values('ID3', NULL,NULL, 768);
insert into #example values('ID4',NULL,'France', 42);
以下是需要我指定列名和类型转换的解决方案:
Here is a solution that requires me to specify the column names and type conversions:
(对联合建议的贡献为jarlh)
(Credit to jarlh for the union suggestion)
select
"ID",
'Country' as "FieldName",
"COUNTRY" as "FieldValue"
from #example
union all
select
"ID",
'Name' as "FieldName",
"NAME" as "FieldValue"
from #example
union all
select
"ID",
'Balance' as "FieldName",
CAST("BALANCE" as NVARCHAR) as "FieldValue"
from #example