Linq 分组 - 聚合,在组之外

发布于 2024-09-09 07:04:45 字数 494 浏览 4 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

童话里做英雄 2024-09-16 07:04:45

使用g.Max(x => x.TableID):(

var errors = from r in MyTable
    group e by new {e.Col1, e.Col2} into g
    orderby g.Count() descending
    select new {MaxId = g.Max(x => x.TableID), 
                Count =  g.Count(), g.Key.Col1, g.Key.Col2};

当然,假设您想要每组中的最大值。)

Use g.Max(x => x.TableID):

var errors = from r in MyTable
    group e by new {e.Col1, e.Col2} into g
    orderby g.Count() descending
    select new {MaxId = g.Max(x => x.TableID), 
                Count =  g.Count(), g.Key.Col1, g.Key.Col2};

(Assuming you want the maximum within each group, of course.)

落墨 2024-09-16 07:04:45

乔恩的回答很好,我只想详细说明一下原因:

问题是,一旦我应用分组,我就无法访问未分组的列

r 超出了范围......这是为什么?

结束查询的两种方式是 selectgroup 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:

The issue is, that as soon as i apply my grouping, I cannot access the non-grouped columns

r went out of scope... why is that?

The two ways of ending a query are select or group by clauses. When you add the query continuation clause into g to the group by, you are saying - the top level elements of the query are g 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 with join on equals into, which is a group join, not a query continuation. Group join does not remove previous variables from scope.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文