I have the following query I am trying to optimize.
EXPLAIN
select clb.f_name, clb.l_name, noofbooks
from (
select f_name, l_name, count(*) as noofbooks from
customer natural join loaned_book
group by f_name, l_name
) as clb
where 3 > (
select count(*) from (
select f_name, l_name, count(*) as noofbooks
from customer natural join loaned_book
group by f_name, l_name
) as clb1
where clb.noofbooks<clb1.noofbooks
)
order by noofbooks desc;
Essentially this query is trying to find the “top three” counts (including ties i.e. not limited to 3) of the no. of books loaned by a customer.
The problem is related to the amount of counts that must be made in the query.
Is it possible to use the count values from the first query to reduce selected rows in the second query without recounting all of the rows?
This is a homework task so I am not expecting a direct answer. Any pointers would be appreciated.
Have a look at the
dense_rankwindow function. You want all the rows that have a dense rank of 3 or less.