SAP HANA 利用case和MAP函数实现行转列:
范例表结构:
CREATE TABLE SCORES(
NAME NVARCHAR(30),
SUBJECT NVARCHAR(30),
SCORE DECIMAL(5,2)
);
范例数据:
insert into SCORES values ('张三','语文',90.00);
insert into SCORES values ('张三','数学',91.00);
insert into SCORES values ('张三','英语',92.00);
insert into SCORES values ('李四','语文',93.00);
insert into SCORES values ('李四','数学',94.00);
insert into SCORES values ('李四','英语',95.00);
insert into SCORES values ('王五','语文',96.00);
insert into SCORES values ('王五','数学',97.00);
insert into SCORES values ('王五','英语',98.00);
使用case实现行转列:
SELECT NAME,
SUM(CASE WHEN SUBJECT='语文' THEN SCORE END) AS "语文",
SUM(CASE WHEN SUBJECT='数学' THEN SCORE END) AS "数学",
SUM(CASE WHEN SUBJECT='英语' THEN SCORE END) AS "英语"
FROM SCORES
GROUP BY NAME
使用MAP()函数实现行转列:
SELECT
NAME,
SUM(MAP(SUBJECT,'语文',SCORE,0)) AS "语文",
SUM(MAP(SUBJECT,'数学',SCORE,0)) AS "数学",
SUM(MAP(SUBJECT,'英语',SCORE,0)) AS "英语"
FROM SCORES
GROUP BY NAME;
MAP 函数:
官方文档:http://help.sap.com/hana/html/sql_function_map.html
语法:MAP (expression, search1, result1 [, search2, result2] ... [, default_result])
参数:MAP为键值对出现的数据结构,MAP函数也类似。expression为要寻找的键值,search1, result1 [, search2, result2] ... 定义相应的键值对,search1为键值,result1 为对应的结果。如果expression在键值对中找到对应的键值,则返回对应的结果,找不到对应的键值,如果有指定default_result值则返回default_result(为默认值),否则返回null
范例:
SELECT MAP(2, 0, 'Zero', 1, 'One', 2, 'Two', 3, 'Three', 'Default') "map" FROM DUMMY;
结果:map Two
SELECT MAP(99, 0, 'Zero', 1, 'One', 2, 'Two', 3, 'Three', 'Default') "map" FROM DUMMY;
结果:map Default
SELECT MAP(99, 0, 'Zero', 1, 'One', 2, 'Two', 3, 'Three') "map" FROM DUMMY;
结果:map NULL