-1

How can I get the top 2 rows returned in this query?

select nomeClube 'Clube', count(Contrato_id_clube) 'NContratos'
from clube, contrato
where (id_clube= Contrato_id_clube)
group by nomeClube
order by count(Contrato_id_clube) desc 

query results

jtbandes
  • 115,675
  • 35
  • 233
  • 266

2 Answers2

0

I believe that you want all groups having the maximum count and your example just happens to have two such rows.

select nomeClube 'Clube', count(Contrato_id_clube) 'NContratos'
from clube inner join contrato on id_clube = Contrato_id_clube
group by nomeClube
having count(Contrato_id_club) = (
    select max(c)
    from (
        select count(Contrato_id_clube) c
        from clube inner join contrato on id_clube = Contrato_id_clube
        group by nomeClube
    ) t
)

The inner join inside the nested query may not be necessary but since you didn't specify the relationship between the tables I've duplicated the entire query there.

shawnt00
  • 16,443
  • 3
  • 17
  • 22
-1

you should put it in an inner select and get top records:

select * from (
select nomeClube 'Clube', count(Contrato_id_clube) 'NContratos'
from clube, contrato
where (id_clube= Contrato_id_clube)
group by nomeClube
order by count(Contrato_id_clube) desc )
limit 2