计算varchar数组Postgres中不同元素的数量

时间:2020-04-27 22:17:44

标签: sql arrays postgresql group-by count

我有一张桌子。

title   | tags
--------------------------
post1   | {tag1,tag2,tag3}
post2   | {tag1,tag2}
post3   | {tag1}

它是用这个做的:

CREATE TABLE post (
    title varchar(10),
    tags varchar(10) array[5]
);

INSERT INTO post (title, tags) VALUES ('post1', '{"tag1", "tag2", "tag3"}');
INSERT INTO post (title, tags) VALUES ('post2', '{"tag1", "tag2"}');
INSERT INTO post (title, tags) VALUES ('post3', '{"tag1"}');

如何计算整个表中数组中不同元素的数量?例如,标签tag1出现在所有三行中,因此它将返回3。我想对每个元素执行此操作,从而创建如下所示的输出:

tag     | COUNT
--------------------------
tag1    | 3
tag2    | 2
tag3    | 1

tags数组将没有任何重复。

1 个答案:

答案 0 :(得分:3)

您可以unnest()数组,然后聚合:

select t.tag, count(*) no_posts
from post p
cross join lateral unnest(p.tags) t(tag)
group by t.tag
order by no_posts desc

Demo on DB Fiddle

tag  | no_posts
:--- | -------:
tag1 |        3
tag2 |        2
tag3 |        1