postgres查询只返回id和count与最大计数

时间:2018-03-15 16:29:39

标签: postgresql

如何才能显示id 4和2,因为它们的计数最高?

SELECT id, count(*) FROM followers GROUP BY id ORDER BY 2 DESC;

id count
4  4
2  4
1  3
3  2

预期结束

id count
4  4
2  4

1 个答案:

答案 0 :(得分:1)

您可以使用如下的公用表表达式(CTE):

 WITH counts AS ( 
 SELECT id, count(*) AS cnt FROM followers GROUP BY id)
 SELECT * FROM counts where cnt = (select MAX(cnt) from counts)