Linq 分组 - 聚合,在组之外
我有一个 SQL 查询,其工作原理如下:
SELECT TOP 100
Max(Table_ID) as Max_ID,
Col1,
Col2,
Col3,
COUNT(*) AS Occurences
FROM myTable
GROUP BY Col1, Col2, Col3
ORDER BY Occurences DESC
如何编写相同的 Linq 查询?
问题是,在我应用分组后,我就无法访问未分组的列Table_ID。
var errors = from r in MyTable
group e by new {e.Col1, e.Col2} into g
orderby g.Count() descending
select new {MaxId = ???, Count = g.Count(), g.Key.Col1, g.Key.Col2};
I've got a SQL query, that works as follows:
SELECT TOP 100
Max(Table_ID) as Max_ID,
Col1,
Col2,
Col3,
COUNT(*) AS Occurences
FROM myTable
GROUP BY Col1, Col2, Col3
ORDER BY Occurences DESC
How can I write an identical Linq query?
The issue is, that as soon as I apply my grouping, I cannot access the non-grouped columns Table_ID in my case.
var errors = from r in MyTable
group e by new {e.Col1, e.Col2} into g
orderby g.Count() descending
select new {MaxId = ???, Count = g.Count(), g.Key.Col1, g.Key.Col2};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
g.Max(x => x.TableID)
:(当然,假设您想要每组中的最大值。)
Use
g.Max(x => x.TableID)
:(Assuming you want the maximum within each group, of course.)
乔恩的回答很好,我只想详细说明一下原因:
r 超出了范围......这是为什么?
结束查询的两种方式是
select
或group by
子句。当您将查询延续子句into g
添加到group by
时,您是在说 - 查询的顶级元素是g
并且所有到目前为止在查询中引入的变量将从范围中删除。如果您在这篇 msdn 文章中搜索单词splice< /strong>,您可以查看示例。
不要将
into
的使用与join on equals into
混淆,后者是组联接,而不是查询延续。组连接不会从作用域中删除以前的变量。Jon's answer is good, I just want to elaborate a little on why:
r went out of scope... why is that?
The two ways of ending a query are
select
orgroup by
clauses. When you add the query continuation clauseinto g
to thegroup by
, you are saying - the top level elements of the query areg
and all variables introduced in the query up to this point are removed from scope.If you search this msdn article for the word splice, you can see samples.
Don't confuse this use of
into
withjoin on equals into
, which is a group join, not a query continuation. Group join does not remove previous variables from scope.