小编Ser*_*gey的帖子

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

我不太擅长 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)

postgresql aggregate array set-returning-functions

9
推荐指数
1
解决办法
1万
查看次数