gpt4 book ai didi

sql - Postgres : Group by clause with predefined set of values

转载 作者:行者123 更新时间:2023-11-29 12:25:30 27 4
gpt4 key购买 nike

我可以对下表进行查询:

表 1:

id       name           source_url
1 object1 www.google.com
2 object2 www.facebook.com
3 object3 www.twitter.com
4 object5 www.google.com

查询:

select count(*) as counts, source_url from Table1 group by source_url

上面的查询将给我以下结果:

counts    source_url
2 www.google.com
1 www.facebook.com
1 www.twitter.com

现在在上面的场景中,我想要的是根据数组中的元素集对 table1 进行分组。示例

arr[] = ["www.facebook.com","www.google.com","www.instagram.com","www.yahoo.com","www.abc.com"]

上表我想要的结果应该是:

counts    source_url
2 www.google.com
1 www.facebook.com
0 www.instagram.com
0 www.yahoo.com
0 www.abc.com

最佳答案

将数组取消嵌套到派生表,左连接到它并使用 COALESCE() 将 NULL 替换为 0:

SELECT COALESCE(counts, 0) AS counts, source_url
FROM unnest('{www.facebook.com,www.google.com,www.instagram.com
,www.yahoo.com,www.abc.com}'::text[]) source_url
LEFT JOIN (
SELECT count(*) AS counts, source_url
FROM Table1
GROUP BY source_url
) USING (source_url);

source_url 使用此短语法成为派生表的表 列名称。如果需要,您可以更详细:

...
FROM unnest(your_array) AS tbl_alias(column_alias)
...

关于sql - Postgres : Group by clause with predefined set of values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40559418/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com