LINQ 跨多个表进行聚合

发布于 2024-09-05 04:12:50 字数 744 浏览 6 评论 0原文

我想在 LINQ to SQL 中复制此查询,但我不太熟悉如何执行此操作。

SELECT A.Recruiter, SUM(O.SaleAmount * I.Commission)  --This sum from fields in two different tables is what I don't know how to replicate
FROM Orders AS O
INNER JOIN Affiliate A ON O.AffiliateID = A.AffiliateID
INNER JOIN Items AS I ON O.ItemID = I.ItemID
GROUP BY A.Recruiter

到目前为止我已经做到了:

from order in ctx.Orders
join item in ctx.Items on order.ItemI == item.ItemID
join affiliate in ctx.Affiliates on order.AffiliateID == affiliate.AffiliateID
group order  //can I only group one table here?
  by affiliate.Recruiter into mygroup
select new { Recruiter = mygroup.Key, Commission = mygroup.Sum(record => record.SaleAmount * ?????) };

I want to replicate this query in LINQ to SQL but am too unfamiliar with how to do it.

SELECT A.Recruiter, SUM(O.SaleAmount * I.Commission)  --This sum from fields in two different tables is what I don't know how to replicate
FROM Orders AS O
INNER JOIN Affiliate A ON O.AffiliateID = A.AffiliateID
INNER JOIN Items AS I ON O.ItemID = I.ItemID
GROUP BY A.Recruiter

I've got this far:

from order in ctx.Orders
join item in ctx.Items on order.ItemI == item.ItemID
join affiliate in ctx.Affiliates on order.AffiliateID == affiliate.AffiliateID
group order  //can I only group one table here?
  by affiliate.Recruiter into mygroup
select new { Recruiter = mygroup.Key, Commission = mygroup.Sum(record => record.SaleAmount * ?????) };

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

抱着落日 2024-09-12 04:12:50
group new {order, item} by affiliate.Recruiter into mygroup 
select new {
  Recruiter = mygroup.Key,
  Commission = mygroup
    .Sum(x => x.order.SaleAmount * x.item.Commission)
}; 

以及编写查询的另一种方法:

from aff in ctx.Affiliates
where aff.orders.Any(order => order.Items.Any())
select new {
  Recruiter = aff.Recruiter,
  Commission = (
    from order in aff.orders
    from item in order.Items
    select item.Commission * order.SaleAmount
    ).Sum()
};
group new {order, item} by affiliate.Recruiter into mygroup 
select new {
  Recruiter = mygroup.Key,
  Commission = mygroup
    .Sum(x => x.order.SaleAmount * x.item.Commission)
}; 

And an alternative way of writing the query:

from aff in ctx.Affiliates
where aff.orders.Any(order => order.Items.Any())
select new {
  Recruiter = aff.Recruiter,
  Commission = (
    from order in aff.orders
    from item in order.Items
    select item.Commission * order.SaleAmount
    ).Sum()
};
忘羡 2024-09-12 04:12:50

试试 linqpad,只需 Google,很棒的工具!

try linqpad, just Google, amazing tool!

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