2

大学表 - UniversityName、UniversityId

租赁表 - LeaseId、BookId、UniversityId、LeaseDate

图书表 - BookId、UniversityId、Category、PageCount。

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

所以,像

UniversityName Category #OfTimesLeased 

我一直在玩它,使用Dense_Ranketc 取得了一些成功 - 但如果有平局,只有一个出现,而我希望他们两个都出现。

当前查询:

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

^无法解决平局问题并获取租借次数最多的图书类型的租借次数。

4

2 回答 2

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
于 2012-11-19T23:19:23.383 回答
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. 这些值将位于不同的行上。

于 2012-11-19T23:17:12.707 回答