Reputation: 13
Hey there guys I had a bit of a problem with the current project I'm working on. The schema is
The question is Display month and the number of books when the maximum number of books were rented
The output is !THE OUTPUT
The code I was able to wrote got me the maximum number of books
select max(count(book_id)) from bookrental.book_rental group by TO_CHAR(rental_start_date,'MON');
Also when I use
select TO_CHAR(rental_start_date,'MON')
from bookrental.book_rental group by(TO_CHAR(rental_start_date,'MON'))
having count(book_id)= (select
max(count(book_id))
from bookrental.book_rental group by TO_CHAR(rental_start_date,'MON'));
Now I need to display the month and the number of books in a single table. I can't manage to join them both.
Can anyone help me out?
Upvotes: 1
Views: 74
Reputation: 1271151
You are much better off using window functions. The equivalent to your attempt would be:
select m.*
from (select TO_CHAR(rental_start_date, 'MON'), count(*) as cnt,
rank() over (order by count(*) desc) as seqnum
from bookrental.book_rental br
group by TO_CHAR(rental_start_date, 'MON')
) m
where seqnum = 1;
But, I don't think this is the best answer for two reasons:
To fix the first problem, I would use trunc()
. To fix the second, I would use row_number()
:
select m.*
from (select trunc(rental_start_date, 'MON'), count(*) as cnt,
row_number() over (order by count(*) desc) as seqnum
from bookrental.book_rental br
group by trunc(rental_start_date, 'MON')
) m
where seqnum = 1;
Finally, this version can be simplified using fetch first
:
select trunc(rental_start_date, 'MON'), count(*) as cnt,
row_number() over (order by count(*) desc) as seqnum
from bookrental.book_rental br
group by trunc(rental_start_date, 'MON')
order by count(*) desc
fetch first 1 row only;
Upvotes: 0
Reputation: 133400
seems you miss the count(book_id)
select TO_CHAR(rental_start_date,'MON') , count(book_id)
from bookrental.book_rental
group by(TO_CHAR(rental_start_date,'MON'))
having count(book_id)= (
select
max(count(book_id))
from bookrental.book_rental
group by TO_CHAR(rental_start_date,'MON'));
Upvotes: 1