SELECT
id,CASEWHEN id <2THEN'a'WHEN id =2THEN'b'ELSE'c'ENDAS caseName
FROM tb_url;
写法二:
SELECT
id,CASE id
WHEN1THEN'a'WHEN2THEN'b'ELSE'c'ENDAS caseName
FROM tb_url;
结合group by的应用:
SELECT
col1 AS col1,MAX(CASE col2 WHEN'c'THEN col3 ELSE0END)AS c,MAX(CASE col2 WHEN'd'THEN col3 ELSE0END)AS d,MAX(CASE col2 WHEN'e'THEN col3 ELSE0END)AS e
FROM
row2col1
GROUPBY
col1;
多行转单列
例:将组内某一字段的多行值合并为一个值,各组的值合并为一列。
SELECT
col1,
col2,
CONCAT_WS(',',COLLECT_LIST(CAST(col3 AS STRING)))AS col3
FROM
row2col2
GROUPBY
col1,col2;
多列转多行
使用union关键字实现多行数据的拼接。
例:
SELECT col1,'c'AS col2, col2 AS col3 FROM col2row1
UNIONALLSELECT col1,'d'AS col2, col2 AS col3 FROM col2row1
UNIONALLSELECT col1,'e'AS col2, col2 AS col3 FROM col2row1;
单列转多行
使用explode函数将一个集合或数组中的每个元素展开,每个元素自成一行。
例:若是字符串类型的数据,需要用split切割为数组。
SELECT
col1,
col2,
lv.col3 AS col3
FROM
col2row2
LATERAL VIEW
EXPLODE(SPLIT(col3,',')) lv AS col3;