Postgresql嵌套select max(sum())

时间:2017-05-20 15:58:16

标签: 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)。

3 个答案:

答案 0 :(得分:1)

您可以使用单一级别的嵌套来执行此操作:

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;

答案 1 :(得分:0)

您可以使用CTE的强大功能来实现这一目标:

WITH count_values 
         AS (SELECT table.attribute, 
                    Count(table.attribute) AS cnt 
             FROM   table 
             GROUP  BY table.attribute), 
         max_values 
         AS (SELECT Max(cnt) AS max_cnt 
             FROM   (SELECT cnt 
                     FROM   count_values) sub) 
    SELECT * 
    FROM   count_values cv 
           JOIN max_values mv 
             ON mv.max_cnt = cv.cnt;

答案 2 :(得分:0)

您可以使用以下等级

with cte as (
    select *, Rank() over(order by cnt desc) as rnk from yourattribute
) select * from cte where rnk = 1