Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
How to get value from a column what has maximum count in postgres?

I understand the MAX function returns a maximum value from a given column for a numeric column. I want to return the maximum count of a column. The below table has two columns maker, product.

maker    product      
A        Printer   
B        Laptop        
B        Laptop      
A        Printer 
A        Monitor
A        Printer
A        Scanner

But when I run the query '''select maker, max(type) from table group by maker; ''' I am getting the result as

maker    product      
A        Monitor   
B        Laptop  

  

I want which product has a maximum count with respect to the maker like below.

maker  product      
A      Printer   
B      Laptop  

  

Note: As maker count differs, we can't set a common number in Having clause.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can do it with RANK() window function:

select t.maker, t.product
from (
  select maker, product, 
    rank() over (partition by maker order by count(*) desc) rn
  from tablename 
  group by maker, product
) t
where t.rn = 1

See the demo.
Results:

| maker | product |
| ----- | ------- |
| A     | Printer |
| B     | Laptop  |
over 4 years ago · Santiago Trujillo Relatório

0

In PostgreSQL, the simplest solution is to use DISTINCT ON:

SELECT DISTINCT ON(maker)
       maker, product
FROM atable
GROUP BY maker, product
ORDER BY maker, count(*) DESC;
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda