2016-05-29 83 views
1

我有圖書館的數據庫,我想最借來標題分配給每個像今年ORACLE SQL選擇MAX(COUNT()),以一年

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

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; 

您的查詢返回擁有了所有年份的整體最大計數,而不是每年最高年/標題組合。