简体   繁体   中英

SELECT values where a value of the subquery equals the max(value) of the same subquery

I'm asked to do this one: return the country with the most customers.(in the case of a tie, display both)

I have this query:

SELECT sub.* 
FROM
    (SELECT country, COUNT(*) AS c 
     FROM customer 
     GROUP BY country) sub
WHERE sub.c = (SELECT MAX(sub.c) FROM sub)

And I get this error:

ERROR: relation "sub" does not exist
LINE 6: WHERE sub.c = (SELECT MAX(sub.c) FROM sub)

When I replace the subquery at the last row by a default value it works properly.

SELECT sub.* 
FROM
    (SELECT country, COUNT(*) AS c 
     FROM customer 
     GROUP BY country) sub
WHERE sub.c = 13

How to get entities where a value of the subquery equals the MAX(value) of the same subquery?

Thank you in advance

This is also works properly, but I want to avoid using the same subquery

SELECT sub.* 
FROM
    (SELECT country, COUNT(*) AS c 
     FROM customer 
     GROUP BY country ) sub
WHERE 
    sub.c = (SELECT MAX(c) 
             FROM 
                 (SELECT country, COUNT(*) AS c 
                  FROM customer 
                  GROUP BY country) sub)

There are several ways to do this:

SELECT country, COUNT(*) AS c 
FROM customer 
GROUP BY country
order by 2 desc
fetch first 1 rows with ties;

The with ties will return more than one row if there are multiple countries with the same highest number of customers. This option (following the SQL standard) was introduced in Postgres 13

Another option is to use a window function together with aggregation:

select country, c
from (
  select country, 
         count(*) as c,
         dense_rank() over (order by count(*) desc) as rnk
  from customer 
  group by country
) t
where rnk = 1;

Window functions are evaluated after the group by, that's why using order by count(*) desc is valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM