关于聚合函数的Postgres“group by”

时间:2013-12-06 10:53:23

标签: sql postgresql aggregate

我有一个返回ID数组的查询,然后使用自定义函数按顺序排序,如下所示: -

SELECT array_sort(my_array) as sort FROM table

这将返回: -

{19,21,24,48}
{19,21,24}
{19,21}
{19}
{16,12,13}
{16,12}
...

我想选择具有不同第一个元素的最长数组,因此从上面的列表中我会得到: -

{19,21,24,48} and {16,12,13}

我怎样才能做到这一点,我尝试将第一个元素作为一个单独的项目拉出来,按长度排序并尝试分组如下: -

SELECT DISTINCT (array_sort(path))[1] as first, array_length(path,1) as plen, array_sort(path) as members FROM table GROUP BY first,plen,members ORDER BY plen DESC

这不起作用,只需命令列表

1 个答案:

答案 0 :(得分:1)

使用distinct on子句:

with cte as (
  select
      array_length(members,1) as plen,
      members[1] as first,
      members
  from (select array_sort(path) as members from table) as a
)
select distinct on (first)
    members
from cte
order by first, plen desc

<强> sql fiddle example