[英]Count number of distinct elements in varchar array Postgres
I have a table.我有一张桌子。
title | tags
--------------------------
post1 | {tag1,tag2,tag3}
post2 | {tag1,tag2}
post3 | {tag1}
It was made with this:它是用这个制作的:
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"}');
How could I count the number of distinct elements in the array for the whole table?我如何计算整个表的数组中不同元素的数量? For example, the tag tag1
appears in all three rows, so it would return 3. I want to do this for every element, creating an output that looks like this:例如,标签tag1
出现在所有三行中,因此它将返回 3。我想对每个元素执行此操作,创建一个 output,如下所示:
tag | COUNT
--------------------------
tag1 | 3
tag2 | 2
tag3 | 1
The tags
array will not have any duplicates. tags
数组不会有任何重复。
You can unnest()
the array, then aggregate:您可以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 : DB Fiddle 上的演示:
tag | no_posts :--- | -------: tag1 | 3 tag2 | 2 tag3 | 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.