sql server没有子查询的最大值计数

我想编写一个T-SQL查询,它不仅返回最大值,还返回具有最大值的行数.必须有比我想出的更好的方法

 --wrong way 
 select LibraryBranchId, max(daysCheckedOut), count(daysCheckedOut) 
 from books group by LibraryBranchId

 LibraryBranchId   Expr1      Expr2
 ----------------------------------
 1                 100       398503  (WRONG!)
 2                 75         94303  (WRONG!)
 3                 120       103950  (WRONG!)

我可以通过INNER JOINing子查询来正确地做到这一点,但这看起来很浪费

 --right way, but seems WAY too long
 select LibraryBranchId,max(daysCheckedOut),count(daysCheckedOut)
 from books inner join 
   ( select LibraryBranchId, max(daysCheckedOut) as maxDaysCheckedOut
     from books group by LibraryBranchId ) as maxbooks 
 on books.LibraryBranchId=maxbooks.LibraryBranchId
 where daysCheckedOut=maxDaysCheckedOut
 group by LibraryBranchId 

 LibraryBranchId   Expr1      Expr2
 ----------------------------------
 1                 100           17  (RIGHT!)
 2                 75            11  (RIGHT!)
 3                 120            2  (RIGHT!)

那么有一种方法就像查询#1一样简单,但是在查询#2中返回正确的结果吗?

MS SQL Server 2000

编辑:我在第一次尝试输入时错过了两个重要的GROUP BY,我添加了它们
编辑:假装Cade Roux编写的版本是我写的

最佳答案 我认为这是对的:

SELECT maxbooks.LibraryBranchId, maxbooks.maxDaysCheckedOut, count(*)
FROM books
INNER JOIN (
    SELECT LibraryBranchId, max(daysCheckedOut) AS maxDaysCheckedOut
    FROM books
    GROUP BY LibraryBranchId
) AS maxbooks
    ON books.LibraryBranchId = maxbooks.LibraryBranchId
    AND books.daysCheckedOut = maxbooks.maxDaysCheckedOut
GROUP BY maxbooks.LibraryBranchId, maxbooks.maxDaysCheckedOut

我不认为有一种更简单的方法 – 从概念上讲,它是两组的交集.关于分支的一组元组和满足该分支的一组tupes.

点赞