gpt4 book ai didi

arrays - 如何使用 postgres 获取不同的数组元素?

转载 作者:行者123 更新时间:2023-11-29 11:38:06 26 4
gpt4 key购买 nike

我在 postgres 中有一个包含重复值的数组。例如:

SELECT cardinality(string_to_array('1,2,3,4,4', ',')::int[]) as foo
=> "foo"=>"5"

我想获取独特的元素,例如:

SELECT cardinality(uniq(string_to_array('1,2,3,4,4', ',')::int[])) as foo
=> -- No function matches the given name and argument types. You might need to add explicit type casts.

我可以在不使用 UNNEST 的情况下在 postgres 中获取数组的唯一元素吗?

最佳答案

我更喜欢这种语法(大约快 5%)

create or replace function public.array_unique(arr anyarray)
returns anyarray as $body$
select array( select distinct unnest($1) )
$body$ language 'sql';

使用:

select array_unique(ARRAY['1','2','3','4','4']);

关于arrays - 如何使用 postgres 获取不同的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40636406/

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