2017-05-20 1 views
0

Meine Suche:Postgresql verschachtelt select max (sum())

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

Der Ausgang ist so etwas wie:

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

Aber ich möchte nur die Max-Werte (A & B).

Antwort

0

Sie die Macht der CTE verwenden können, dies erreichen:

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; 
+0

Prost auf dich und @klin alle Ressourcen, die ich gefunden habe, hat nicht für mich gearbeitet! – AnnoyedGuy

+0

Froh, Ihnen zu helfen @AnnoyedGuy –

0

Sie Rang wie unten

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

Sie können dies tun mit einer einzigen Ebene der Verschachtelung verwenden können:

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;