oracle - 每组最大值

时间:2012-11-19 23:08:02

标签: sql oracle

大学表 - UniversityName,UniversityId

租赁表 - LeaseId,BookId,UniversityId,LeaseDate

书籍表 - BookId,UniversityId,Category,PageCount。

对于每所大学,我必须找到租借书籍数量最多的类别。

所以,像

UniversityName Category #OfTimesLeased 

我一直在使用Dense_Rank等方面取得了一些成功 - 但如果有一个平局,只有其中一个出现,而我希望它们都显示出来。

当前查询:

select b.UniversityId, MAX(tempTable.type) KEEP (DENSE_RANK FIRST ORDER BY tempTable.counter DESC)
from book b 
join 
(select count(l.leaseid) AS counter, b.category, b.universityid
from lease l
join book b
on b.bookid =l.bookid AND b.universityid=r.universityid
 group by b.category, b.universityid) tempTable
 on counterTable.universityid= b.universityid
 group by b.universityid

^无法解决领带问题,并获得最多租借图书类型的租约数量。

2 个答案:

答案 0 :(得分:1)

试试这个

WITH CTE AS
(
SELECT UniversityName, Category, Count(*) NumOfTimesLeased 
FROM University u
INNER JOIN Book b on u.UniversityId = b.UniversityId
INNER JOIN Lease l on b.bookid = l.bookid and b.UniversityId = l.UniversityId
GROUP BY UniversityName, Category    
), 
CTE2 AS (
SELECT UniversityName, Category, NumOfTimesLeased,
RANK() OVER (PARTITION BY UniversityName 
             ORDER BY NumOfTimesLeased DESC) Rnk
FROM CTE)

SELECT * FROM CTE2 WHERE Rnk = 1

答案 1 :(得分:0)

您使用分析函数走在正确的轨道上:

select Univerity, Category, NumLeased
from (select t.*,
             row_number() over (partition by university order by Numleased desc) as seqnum
      from (select l.university, b.category, count(*) as NumLeased
            from lease l join
                 book b
                 on l.bookid = b.bookid
            group by l.university, b.category
           ) t
     ) t
where seqnum = 1

我使用row_number()因为你只需要一个顶部值。当您查找“1”以外的值时,Rank和dense_rank会更有用。

如果您希望在出现平局时显示最高值,请使用dense_rank代替row_number。值将在不同的行上。