从爆炸数据的唯一列表创建PostgreSQL视图

问题描述

当我发出此请求时:

SELECT mycol FROM mytable WHERE mycol IS NOT NULL;

我得到这样的结果:

foo / bar / hello
foo / hello
foo / bar

每行的值都用/(空格,斜杠,空格)分隔。

如何创建一个带有count唯一值列表的视图?

bar 2
foo 3
hello 2

解决方法

您可以在横向联接中使用regexp_split_to_table()将字符串拆分为行,然后进行汇总:

select x.val,count(*) cnt
from mytable t
cross join lateral regexp_split_to_table(t.mycol,'\s/\s') as x(val)
group by x.val

Demo on DB Fiddle

val   | cnt
:---- | --:
bar   |   2
foo   |   3
hello |   2
,

您可以结合使用string_to_arrayunnest来实现这一目标。

尝试以下查询

select 
unnest(string_to_array(mycol,' / ')),count(*) 
from mytable 
where mycol IS NOT NULL 
group by 1

DEMO