使用LINQ to SQL,我怎么找表中的一列的最小值和最大值? [英] Using Linq to SQL, how do I find min and max of a column in a table?

查看:131
本文介绍了使用LINQ to SQL,我怎么找表中的一列的最小值和最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到获得列的最小值和最大值在一个单一的LINQ到SQL往返表的最快方式。所以我知道这将在两个往返工作:

I want to find the fastest way to get the min and max of a column in a table with a single Linq to SQL roundtrip. So I know this would work in two roundtrips:

int min = MyTable.Min(row => row.FavoriteNumber);
int max = MyTable.Max(row => row.FavoriteNumber);



我知道我可以使用,但我不要条款有一个组,我要聚集在整个表!我不能没有先分组使用.Min。我曾尝试这样的:

I know I can use group but I don't have a group by clause, I want to aggregate over the whole table! And I can't use the .Min without grouping first. I did try this:

from row in MyTable 
group row by true into r 
select new { 
    min = r.Min(z => z.FavoriteNumber), 
    max = r.Max(z => z.FavoriteNumber) 
}

但是,疯狂的一群条款似乎傻了,它使SQL比它需要更复杂的。

But that crazy group clause seems silly, and the SQL it makes is more complex than it needs to be.

那么,有没有什么办法可以只得到正确的SQL出

So, is there any way to just get the correct SQL out?

编辑:?这些家伙没有太:的 http://stackoverflow.com/questions/1597181/linq-to-sql-如何对聚集型不-A-组由 ......通过LINQ设计师瘸腿的监督,如果真的没有答案

These guys failed too: http://stackoverflow.com/questions/1597181/linq-to-sql-how-to-aggregate-without-a-group-by ... lame oversight by LINQ designers if there's really no answer.

编辑2:我看着在SQL Server Management Studio中执行计划的分析我自己的解决方案(由子句中的无厘头恒集团),它看起来对我来说,它等同于所产生的计划:

EDIT 2: I looked at my own solution (with the nonsensical constant group by clause) in the SQL Server Management Studio execution plan analysis, and it looks to me like it is identical to the plan generated by:

SELECT MIN(FavoriteNumber), MAX(FavoriteNumber)
FROM MyTable

所以,除非有人能拿出一个简单的有或相等的好答案,我想我必须把它标记为回答按我自己。思考?

so unless someone can come up with a simpler-or-equally-as-good answer, I think I have to mark it as answered-by-myself. Thoughts?

推荐答案

如问题所说,这种方法似乎是实际产生最佳的SQL代码,因此,尽管它看起来有点松鼠在LINQ,它应该是最佳的性能,明智的。

As stated in the question, this method seems to actually generate optimal SQL code, so while it looks a bit squirrely in LINQ, it should be optimal performance-wise.

from row in MyTable  
group row by true into r  
select new {  
    min = r.Min(z => z.FavoriteNumber),  
    max = r.Max(z => z.FavoriteNumber)  
} 

这篇关于使用LINQ to SQL,我怎么找表中的一列的最小值和最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆