0

I have a table with schema and data as follows

id,winner,season  
1, Chelsea, 2014 
2, Chelsea, 2014 
3, Chelsea, 2015 
4, Arsenal, 2014

. .

and so on.

Basically, there is an entry in there for every match of every season.

I need to query and identify the team that won the maximum number of matches for each season.

I got till retrieving the maximum number of matches in each season but I am not able to retrieve the name of the team that had the maximum. Any leads?

with  t1 as
(select count(winner) as cnt, winner, season from matches group by winner,season)
select max(cnt),season from t1 group by season
user3409426
  • 23
  • 1
  • 6

1 Answers1

3

This one should work:

select t2.*
from (
select season, max(totalwins) as totalwins from (
select season, winner, count(*) as totalwins
  from matches t
  group by season, winner
) s1 group by season) w join
(select season, winner, count(*) as totalwins
  from matches t
  group by season, winner
) t2 on t2.season = w.season and t2.totalwins = w.totalwins;

Result:

season  winner  totalwins
------  ------- ---------
2014    Chelsea 2
2015    Arsenal 1
2015    Chelsea 1
The Impaler
  • 45,731
  • 9
  • 39
  • 76