分组时如何联合数组?

How to union an array when grouping?

我正在尝试将多个数组列合并为一个具有不同元素的列,然后计算不同元素的数量。我怎样才能在 postgres 中做类似的事情?

 create temp table t as ( select 'james' as fn, array ['bond', 'milner'] as ln );

 create temp table tt as ( select 'james' as fn, array ['mcface', 'milner'] as ln );
-- expected value: james, 3

    select x.name,
           array_length()-- what to do here?
    from (
             select fn, ln
             from t
             union
             select fn, ln
             from tt
         ) as x
    group by x.name

你(想要)为什么使用数组?那是不需要的。只需使用 UNION 派生 table,消除重复,GROUP BY name 并使用 count().

SELECT name,
       count(*)
       FROM (SELECT name,
                    ln
                    FROM t
             UNION
             SELECT name,
                    ln
                    FROM tt) AS x
       GROUP BY name;

db<>fiddle

旁注:9.3 暂时不受支持。考虑升级。

您应该取消嵌套内部查询中的数组:

select x.fn,
       count(elem) 
from (
         select fn, unnest(ln) as elem
         from t
         union
         select fn, unnest(ln) as elem
         from tt
     ) as x
group by x.fn

Db<>fiddle.