如何计算由ARRAY_AGG()
在PostgresQL中创建的数组对象中不同元素的数量?这是一个用于讨论目的的玩具示例:
SELECT ARRAY_AGG (first_name || ' ' || last_name) actors
FROM film
我已经尝试过ARRAY_LENGTH()
,LENGTH()
等,就像这样:
SELECT ARRAY_LENGTH(a.actors)
FROM (SELECT ARRAY_AGG (first_name || ' ' || last_name) actors
FROM film) a;
但是我得到一个错误:
function array_length(integer[]) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Position: 208
所以我尝试了(2):
SELECT ARRAY_LENGTH( CAST(COALESCE(a.actors, '0') AS integer) )
FROM (SELECT ARRAY_AGG (first_name || ' ' || last_name) actors
FROM film) a;
但是我得到了错误:
malformed array literal: "0"
Detail: Array value must start with "{" or dimension information.
Position: 119
答案 0 :(得分:2)
函数array_length(anyarray,int)需要两个元素,例如array和维度:
Select array_length(array[1,2,3], 1);
结果: 3
答案 1 :(得分:0)
如果您只处理一个维度数组,则cardinality()
更易于使用:
SELECT cardinality(ARRAY_LENGTH(a.actors))
FROM (
SELECT ARRAY_AGG (first_name || ' ' || last_name) actors
FROM film
) a;