我在 psql 中有这两个查询:
select a.name, a.port, count(a.id) as cont
from a
group by a.name, a.port
order by cont desc
limit 5;
select a.name, a.ip, count(a.id) as cont
from a
group by a.name, a.ip
order by cont desc
limit 5;
我想编写一个查询,通过这 2 个组的计数获取前 5 条记录,并显示它们的 a.name、count、a.port/a.ip 字段。有谁知道如何构造此查询?
我想要这样的东西:
select a.name, a.port or a.ip, count(a.id) as cont
from a
group by a.name, a.port or a.ip
order by cont desc
limit 5;
感谢任何有关如何在 postgres 中执行此操作的指导。
最佳答案
假设 port
/ip
有兼容的类型,那么横向连接是最好的解决方案:
select a.name, v.which, v.val, count(*) as cont
from a cross join lateral
(values ('ip', ip), ('port', port)
) v(which, val)
group by a.name, v.which, v.val
order by cont desc
limit 5;
如果它们的类型不同,可以使用::text
将它们转换为字符串:
(values ('ip', ip::text), ('port', port::text)
) v(which, val)
关于sql - 或者在 postgres 中按字段分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154749/