基于其他列值合并行值的Presto SQL查询方案求助
Presto SQL实现按客户ID合并物业ID列数据
基础数据表
| 客户ID | 物业ID | 客户预订数 | 客户取消数 |
|---|---|---|---|
| A | 1 | 0 | 1 |
| B | 2 | 10 | 1 |
| C | 3 | 100 | 1 |
| C | 4 | 100 | 1 |
| D | 5 | 20 | 1 |
当前使用的SQL查询
select customer_id, property_id, bookings_per_customer, cancellations_per_customer from table
期望合并结果
| 客户ID | 物业ID | 客户预订数 | 客户取消数 |
|---|---|---|---|
| A | 1 | 0 | 1 |
| B | 2 | 10 | 1 |
| C | 3 , 4 | 100 | 1 |
| D | 5 | 20 | 1 |
Presto SQL解决方案
在Presto中可以用string_agg()函数拼接同一客户的多个物业ID,同时按客户ID、预订数、取消数分组(这些字段对同一客户取值一致),具体语句如下:
select customer_id, string_agg(property_id, ' , ') as property_id, bookings_per_customer, cancellations_per_customer from table group by customer_id, bookings_per_customer, cancellations_per_customer
说明
string_agg(字段名, 分隔符):将分组内指定字段的所有值用指定分隔符拼接成字符串,这里用' , '匹配期望结果的格式。group by子句需包含所有非聚合字段,确保同一客户的相同统计值会被合并。
内容的提问来源于stack exchange,提问作者bobbytici
相关产品推荐
相关产品推荐

