你能帮忙把它翻译成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();
答案 0 :(得分:1)
查询已经结束,只需要进行重组以使其跨越终点。主要问题是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()
聚合可以访问您想要的表格Sum()
添加了一个lambda,以便它在传入的每一行上执行。(这就是你在linq中处理Sum()
和其他聚合函数的方式,以匹配你在SQL。)