如何使用 LINQ to SQL 中的 Sum, GroupBy 计算总计
本文关键字:GroupBy 计算 Sum 中的 何使用 LINQ to SQL | 更新日期: 2024-12-05 19:44:46
你能帮忙把它翻译成linq c#吗,我试过但没有成功。
SELECT od.ProductID, p.productName, SUM (od.UnitPrice * od.Quantity) as total
FROM products p
JOIN [order Details] od ON od.ProductId = p.ProductId
GROUP BY od.ProductId, p.productName
ORDER BY productID ASC
我已经尝试过这个,但它给了我一个错误:
var query =
(from od in dal.Order_Details
join p in dal.Products on od.ProductID equals p.ProductID
group p by new {od.ProductID, p.ProductName}
into g
select new pintar
{
// orderId = g.Key.OrderID,
productId = g.Key.ProductID,
productName = g.Key.ProductName,
UnitPrice = od.UnitPrice,
Quantity = od.Quantity,
Discount = od.Discount,
total = sum((g.Key.UnitPrice * g.Key.Quantity))
}
).ToList();
查询已经结束,它只需要重组就可以让它越过终点线。主要问题是select
子句中存在混合的聚合和列结果,如注释中所述。我认为这应该这样做:
var query =
(from od in dal.Order_Details
join p in dal.Products on od.ProductID equals p.ProductID
group od by new {od.ProductID, p.ProductName}
into g
select new pintar
{
productId = g.Key.ProductID,
productName = g.Key.ProductName,
total = g.Sum(a => a.UnitPrice * a.Quantity))
}
).ToList();
我在这里做的三件事是:
-
group od by
而不是group p by
,以便您的Sum()
聚合可以访问所需的表 - 删除了 SQL 查询中没有的所有其他列,因为这扩大了查询转换的范围并使其难以调试
- 向
Sum()
中添加了一个 lambda,以便它在传入的每一行上执行。(这是您在 linq 中处理Sum()
和其他聚合函数的方式,以匹配您在 SQL 中的方式。