简体   繁体   English

如何在 SQL 中逆透视? (SAP HANA)(列到行)

[英]How to Unpivot in SQL? (SAP HANA) (Columns to rows)

I need to unpivot some data in SAP HANA.我需要在 SAP HANA 中取消旋转一些数据。 I set up an example table to try it out on, but I still can't get anywhere.我设置了一个示例表来试用它,但我仍然无法到达任何地方。

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.实际表包含 1000 个 ID 和约 50 列,但我想对许多表执行此操作,因此虽然我可以指定 FieldNames(原始列),但最好有一个自动化解决方案。

Here is the example table I setup:这是我设置的示例表:

在此处输入图片说明

I would like to get the results into this form:我想将结果转化为这种形式:

在此处输入图片说明

Note: The '?'注意:“?” represents NULL.代表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);

Creating a key-value store like table is the wrong thing to do in most situations that involve SQL databases.在大多数涉及 SQL 数据库的情况下,创建像表这样的键值存储是错误的。 That said, with HANA SDI/SDQ (Smart data Integration/smart data quality) you can create a “flow graph” (basically a data transformation process) that does the pivot/unpivot operation without having to code much.也就是说,使用 HANA SDI/SDQ(智能数据集成/智能数据质量),您可以创建一个“流程图”(基本上是一个数据转换过程),无需编写太多代码即可执行数据透视/逆透视操作。

Here is a solution that requires me to specify the column names and type conversions:这是一个需要我指定列名和类型转换的解决方案:

(Credit to jarlh for the union suggestion) (感谢 jarlh 的工会建议)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM