7

我有 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

我在正确的轨道上吗?我该怎么做才能得到这两个计数?

4

1 回答 1

15
  1. 对于左连接 - 我建议使用 afromwhereaDefaultIfEmpty

  2. 您需要使用匿名类型进行分组才能对多个参数进行分组

值不能为空。参数名称:内

任何连接属性都可以为空吗?

 var qry = 
        from Cust in tblCust
        from Order in tblOrder.Where(x => Cust.CustID == x.CustID)
                              .DefaultIfEmpty()
        from Item in tblItem.Where(x => Order.OrderID == x.OrderID)
                            .DefaultIfEmpty()
        group new { Cust, Order.OrderId, Item.ItemId } by new { Cust.CustID, Cust.CustName } into grp
        let numItems = grp.Select(x => x.ItemId).Distinct().Count()
        orderby numItems 
        select new
        {
            ID = grp.Key.CustID,
            Name = grp.Key.CustName,
            numOrders = grp.Select(x => x.OrderId).Distinct().Count(),
            numItems,
        };
于 2012-07-20T17:03:44.523 回答