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

时间:2009-07-13 17:50:58

标签: sql sql-server sql-server-2000 count max

我想编写一个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编写的版本是我写的

4 个答案:

答案 0 :(得分:2)

我认为这是对的:

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。

答案 1 :(得分:0)

最简单的方法是获取您的LibraryBranchId并选择您的dayscheckedout 然后在编写代码的任何地方以编程方式对它们进行计数,并以编程方式获得最大dayscheckout。

答案 2 :(得分:0)

这个怎么样?

select LibraryBranchId, MAX(daysCheckedOut), count(daysCheckedOut)
from books B
where daysCheckedOut = (select MAX(daysCheckedOut) from books where LibraryBranchID = B.LibraryBranchID)
group by LibraryBranchId 

答案 3 :(得分:0)

另一种“浪费”的方式:

select LibraryBranchId, avg(daysCheckedOut) as maxDaysCheckedOut, count(*)
from
(
    select LibraryBranchId, daysCheckedOut
    from books b1
    where not exists 
    (
        select *
        from books b2
        where b2.LibraryBranchId = b1.LibraryBranchId
        and b2.daysCheckedOut > b1.daysCheckedOut
     )
) t
group by LibraryBranchId