我不太擅长 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)
我怎样才能
像这样:
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)