Break the problem into logical steps:
1) Get the counts by account and class:
Code:
select account, class, count(*) cnt
from ...
group by account, class;
2) Get the max count per account:
Code:
select account, max(cnt) maxcnt
from
( select account, class, count(*) cnt
from ...
group by account, class
)
group by account;
3) Get details of account and class for those max(cnt) values:
Code:
select account, class
from
( select account, class, count(*) cnt
from ...
group by account, class
)
where (account, cnt) in
( select account, max(cnt) maxcnt
from
( select account, class, count(*) cnt
from ...
group by account, class
)
group by account
);
Now that does look messy. If your DBMS supports the WITH clause then you can rewrite as:
Code:
with temp as
( select account, class, count(*) cnt
from ...
group by account, class
)
select account, class
from temp
where (account, cnt) in
( select account, max(cnt) maxcnt
from temp
group by account
);