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

无人久伴 提交于 2021-01-28 17:46:54

问题


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.

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.

Here is the example table I setup:

I would like to get the results into this form:

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);

回答1:


Creating a key-value store like table is the wrong thing to do in most situations that involve SQL databases. 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.




回答2:


Here is a solution that requires me to specify the column names and type conversions:

(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


来源:https://stackoverflow.com/questions/60073446/how-to-unpivot-in-sql-sap-hana-columns-to-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!