数组整数[]:如何获取表中的所有不同值并对其进行计数?

Ser*_*gey 9 postgresql aggregate array set-returning-functions

我不太擅长 SQL (PostgreSQL)。这是我想要做的:

我有一张表,字段:

id SERIAL
inet INET
ports integer[]

 id |    inet    | ports 
----+------------+------------
  2 | 1.2.2.1    | {80}
  1 | 1.2.3.4    | {80,12}
  ...
Run Code Online (Sandbox Code Playgroud)

我怎样才能

  1. 获取此表中所有使用的“端口”值:80、12
  2. 计算特定端口上有多少个 inet 地址:

像这样:

  port  | count
--------+------------
 12     | 1
 80     | 2
  ...
Run Code Online (Sandbox Code Playgroud)

如果有人正在寻找它的 Django 版本:

class Unnest(Func):
    function = 'UNNEST'

Model.objects \
.annotate(port=Unnest('ports', distinct=True)) \
.values('port') \
.annotate(count=Count('port')) \
.order_by('-count', '-port')
Run Code Online (Sandbox Code Playgroud)

jja*_*nes 14

您可以使用UNNEST.

select unnest(ports) as port, count(*) from foo group by port;
Run Code Online (Sandbox Code Playgroud)

在同一个查询(或同一个选择列表,无论如何)中使用多个 UNNEST 会令人困惑,最好避免。