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


9

我对SQL(PostgreSQL)不太满意。这是我想做的:

我有一张桌子,字段:

id SERIAL
inet INET
ports integer[]

 id |    inet    | ports 
----+------------+------------
  2 | 1.2.2.1    | {80}
  1 | 1.2.3.4    | {80,12}
  ...

我怎么能够

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

像这样:

  port  | count
--------+------------
 12     | 1
 80     | 2
  ...

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

class Unnest(Func):
    function = 'UNNEST'

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

Answers:


12

您可以使用UNNEST

select unnest(ports) as port, count(*) from foo group by port;

在同一个查询(或同一个选择列表)中使用多个UNNEST会造成混淆,最好避免。


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.