Search code examples
postgresqlcountsubquerymax

How to combine max and count in one query


I have a simple question about 'max' and 'count' functions.

I read some posts already but they don't satisfy me or i cannot understand them well enough to use them

I tried to refer to this

Here is my query:

select wojewodztwo, count(*) as liczba from wojewodztwa 

inner join powiaty on wojewodztwa.klwoj = powiaty.klwoj 
inner join gminy on powiaty.klpow = gminy.klpow 
inner join miejscowosci on gminy.klgm = miejscowosci.klgm 

where miejscowosc = 'Nowy Dwór' 
group by wojewodztwo order by count(*) desc

And the result of this query looks like this

enter image description here

Now i want to get only max value rows as the answer. I don't want to use Limit 2 I thought of doing something like max(count) but it seems that aggregate functions cannot be stacked on one of eachother


Solution

  • Using a windowed function and a CTE will be quicker and more elegant:

    WITH
    T AS
    (
    SELECT wojewodztwo, COUNT(*) as liczba, MAX(COUNT(*)) OVER() AS MAX_liczba  
    FROM   wojewodztwa 
           INNER JOIN powiaty 
              ON wojewodztwa.klwoj = powiaty.klwoj 
           INNER JOIN gminy 
              ON powiaty.klpow = gminy.klpow 
           INNER JOIN miejscowosci 
              ON gminy.klgm = miejscowosci.klgm 
    WHERE  miejscowosc = 'Nowy Dwór' 
    GROUP  BY wojewodztwo
    )
    SELECT wojewodztwo, liczba
    FROM   T
    WHERE  liczba = MAX_liczba;