1. Row to column (combine multiple rows of data into one column)
1.1 source table person_info:
name
constellation
blood_type
Zhang San
Aries
A
Li Si
Sagittarius
A
Wang Wu
Aries
B
Zhao Liu
Aries
A
Liu Qi
Sagittarius
A
1.2 Requirements: Classify people with the same constellation and blood type together, as shown in the following table:
cbt
name
Archer, A
Li Si, Liu Qi
Aries, A
Zhang San, Zhao Liu
Aries, B
Wang Wu
1.3 function:
concat(字段1,分割符,字段2)--将一行的多个字符串合并成一个字符串
concat_ws(分割符,字段1)--将一列的多个字符串按指定分隔符合并成一个字符串 group by ...
collect_set(字段)--合并的字段去重 搭配使用 concat_ws(',',collect_set(name))
collect_list(字段)--合并的字段不去重 concat_ws(',',collect_list(name))
1.4 code:
select
cbt,
concat_ws(',',collect_list(name))as name
from(select
concat(constellation,',',blood_type)as cbt,
name
from person_info
) tmp
groupby cbt
;