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)
我怎样才能
像这样:
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 会令人困惑,最好避免。
归档时间: |
|
查看次数: |
12202 次 |
最近记录: |