业务需求:
字段字符串的元素使用逗号拼接,现在合并这个字段,并对中的元素进行去重。
方法
使用regexp_split_to_table对字段先拆分,并使用string_agg合并
select
string_agg(distinct name,',') as name,
user_type
from (
select user_type,regexp_split_to_table(name,',') as name
from user_tb
)
group by user_type
存在的问题
如果被拆分的字段为null,则对应是这条数据就被筛掉。导致数据缺失。如上述的name为空,则会漏掉某个user_type。
解决方法
可以在拆分之前对字段进行判空操作。如这里使用coalesce判断为null则为空字符串。
select
string_agg(distinct name) as name,
user_type
from (
select user_type,regexp_split_to_table(coalesce(name,'')) as name
from user_tb
)
group by user_type
这样就能保证表中的每个user_type都有。
hy:55
人生没有偶然,只有一次又一次的命中注定。