我有 3 个表,Cust、Order 和 Item,其中包含以下相关字段:
Cust - CustID, CustName
Order - OrderID, CustID
Item - ItemID, OrderID
我想找到每个客户的订单和商品总数。
这是一个 SQL 语句,它生成我想要的内容,一个客户列表,其中包含每个客户的订单总数和订购的商品总数。
SELECT
Cust.CustID, Cust.CustName,
count(DISTINCT Order.OrderID) AS numOrders,
count(DISTINCT Item.ItemID ) AS numItems
FROM Cust
LEFT JOIN Order ON Order.CustID = Cust.CustID
LEFT JOIN Item ON Item.OrderID = Order.OrderID
GROUP BY Cust.CustID, Cust.CustName
ORDER BY numItems
我将其转换为 LINQ 的第一次尝试是仅计算项目并得出以下结论:
var qry = from Cust in tblCust
join Order in tblOrder on Cust.CustID equals Order.CustID
join Item in tblItem on Order.OrderID equals Item.OrderID
group Cust by new {CustID = Cust.CustID, CustName = Cust.CustName} into grp
orderby grp.Count()
select new
{
ID = grp.Key.CustID,
Name = grp.Key.CustName,
Cnt = grp.Count()
};
使用此代码,我得到了异常:
Value cannot be null. Parameter name: inner
我在正确的轨道上吗?我该怎么做才能得到这两个计数?