需求:对用户的订单进行分析,将不同订单类型分别多少单展示出来,每个用户一行
原数据:
user | order_type | order_number |
user1 | delivered | 10 |
user2 | returned | 1 |
user1 | returned | 3 |
user2 | delivered | 20 |
user | order |
user1 | delivered(10),returned(3) |
user2 | delivered(20),returned(1) |
1.使用concat()函数将order_type和order_number连接起来
concat(order_type,'(',order_number,')')
user | order |
user1 | delivered(10) |
user2 | returned(1) |
user1 | returned(3) |
user2 | delivered(20) |
将上面列表中一个user可能会占用多行转换为每个user占一行的目标表格式,实际是“列转行”
select user,concat_ws(',',collect_set(concat(order_type,'(',order_number,')'))) order from table group by user
order是别名
collect_set的作用:
(1)去重,对group by后面的user进行去重
(2)对group by以后属于同一user的形成一个集合,结合concat_ws对集合中元素使用,进行分隔形成字符串