Postgres的:指望从子查询
问题描述:
独特的数组项。如果我的子查询富解放行: -Postgres的:指望从子查询
ID, USERS
1 {23129}
2 {23142}
3 {23300,23300}
4 {23129,23300}
我如何使用窗函数得到独特的用户的数量在查询,如: -
SELECT ... FROM (<subquery>) FOO
我尝试这样做: -
array_length(array_agg(array_length(array(SELECT Distinct unnest(users))),1)) over(), 1)
但得到的错误,该阵列的尺寸是不一样的
注意:我无法更改子查询来解决此问题。
我能得到的ID在一个阵列如下: -
string_to_array(string_agg(array_to_string(user_ids, ','), ',') over(),',')
但它们并不明显。
答
您可以随时使用已知alghoritm在一个简单的SQL函数:
create or replace function array_unique_elements(arr anyarray)
returns integer
language sql immutable
as $$
select count(distinct a)::int
from unnest(arr) a
$$;
用途:
select *, array_unique_elements(users)
from (
values
(1, '{23129}'::int[]),
(2, '{23142}'),
(3, '{23300,23300}'),
(4, '{23129,23300}')
) foo (id, users)
id | users | array_unique_elements
----+---------------+-----------------------
1 | {23129} | 1
2 | {23142} | 1
3 | {23300,23300} | 1
4 | {23129,23300} | 2
(4 rows)
答
你过于复杂的事情 - 你可以UNNEST数组,然后从中查询重复计数:
SELECT COUNT(DISTINCT u)
FROM (SELECT UNNEST(users) AS u
FROM mytable) t
+0
感谢,但子查询不能改变 – CitizenFish
答
我也只是算不同的Mureinik建议。你得到
以及有关错误 - 这里是紧语法示例与array_length
:
t=# with a(v) as (values('{1,2}'::int[]),('{2,3}'))
select array_length(array_agg(distinct unnest),1) from (
select unnest(v) from a
) a;
array_length
--------------
3
(1 row)
当然它将不与窗口聚集 - 只有GROUP BY
感谢您的答案,问题是子查询不能改变。 – CitizenFish
'SELECT COUNT(不同BAR)FROM()FOO,UNNEST(FOO.USERS)AS BAR' –
Abelisto