Postgresql 嵌套选择 max(sum())

标签 postgresql nested aggregate

我的查询:

select table.attribute, count(table.attribute) AS cnt from table
group by table.attribute
order by cnt desc;

输出是这样的:

 attribute | cnt 
-----------+-----
 A         |   2
 B         |   2
 G         |   1
 F         |   1

但我只想要最大值(A 和 B)。

最佳答案

您可以使用单层嵌套来做到这一点:

select attribute, 
       cnt
from (
  select attribute, 
         count(*) AS cnt, 
         max(count(*)) over () as max_cnt
  from t
  group by attribute
) t
where cnt = max_cnt;

关于Postgresql 嵌套选择 max(sum()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44087973/

相关文章:

database - postgresql 中带有字母(非数字)的列的数据类型

c - 需要 build 一个金字塔,数字和星星之间有空格

C++程序,使用嵌套循环设计

sql - LISTAGG 失败,SQLCODE=-440

sql - 如何将 DISTINCT 与 string_agg() 和 to_timestamp() 一起使用?

PostgreSQL - 将数据从一个表、数据库、服务器复制到另一个表、另一个数据库、服务器

ruby-on-rails - Rails:ActiveRecord::Base 没有连接池

r - 使用 data.table 聚合小计和总计

java - Spring JPA 无法将参数传递到引号中

validation - angular2 - 在父 FormGroup 的子组件中验证 FormControlName