ORACLE SQL选择max(count())到年份

时间:2016-05-29 13:07:09

标签: sql oracle select max

我有图书馆数据库,我正在尝试为每年分配最多的借阅标题,如

2015 - The Great Gatsby
2014 - Da vinci code
2013 - Harry Potter
....

我试过这个,但我不确定

select to_char(borrow_date,'YYYY'),title_name
from k_title
join k_book
using(title_id)
join k_rent_books
using(book_id)
group by to_char(borrow_date,'YYYY'),title_name
having count(title_id) = (
select max(cnt) FROM(select count(title_name) as cnt
from k_title
join k_book
using(title_id)
join k_rent_books
using(book_id)
group by title_id,title_name,to_char(borrow_date,'YYYY')));

我只有3个结果

2016 - Shogun
2006 - The Revolt of Mamie Stover
1996 - The Great Gatsby

我会很乐意提供任何帮助:)

1 个答案:

答案 0 :(得分:1)

Oracle能够很好地获取聚合中的第一个或最后一个值(而不是min()max())。这需要使用名为keep的内容。

所以,表达你想做的事情的方式是:

select yyyy,
       max(title_name) keep (dense_rank first order by cnt desc) as title_name
from (select to_char(borrow_date, 'YYYY') as yyyy,
             title_name, count(*) as cnt
      from k_title t join
           k_book b
           using (title_id) join
           k_rent_books
           using (book_id)
      group by to_char(borrow_date, 'YYYY'), title_name
    ) yt
group by yyyy;

您的查询返回的年份/标题组合具有所有年份的总体最大数量,而不是每年的最大数量。