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一样简单,但返回正确的结果,如查询#1 2?
MS SQL Server 2000
编辑:在我第一次尝试输入此内容时,我错过了上面两个重要的 GROUP BY,我已添加它们 编辑:假装凯德·鲁克斯写的版本就是我写的
I want to write a T-SQL query which returns not only the maximum value, but the number of rows having the maximum value. There must be a better way than what I have come up with
--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!)
I can do this correctly by INNER JOINing a subquery but it seems wasteful
--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!)
So is there a way that is as simple as query #1, but returns the correct result as in query #2?
MS SQL Server 2000
EDIT: I missed two important GROUP BYs above on my first try at entering this, I have added them
EDIT: Pretend that the version that Cade Roux wrote is what I wrote
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为这是正确的:
我认为没有更简单的方法 - 从概念上讲,它是两个集合的交集。 关于分支的元组集合和满足该条件的元组集合。
I think that's right:
I don't think there's a simpler way - conceptually, it's the intersection of two sets. The set of tuples about the branches and the set of tupes satisfying that.
最简单的方法是获取您的 LibraryBranchId 并选择您的签出日期
然后无论您在何处编写代码,都以编程方式对它们进行计数,并以编程方式获取最大天数。
The easiest way to do this is to get your LibraryBranchId's and select your dayscheckedout
then count them programmatically wherever you write the code and get the max dayscheckedout programmatically also.
这个怎么样?
How about this?
另一种“浪费”的方式:
Another "wasteful" way: