具有多个连接的LINQ to SQL,group by和count

时间:2012-07-20 16:56:15

标签: linq-to-sql

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

我是否在正确的轨道上?我需要做些什么来获得两个计数?

1 个答案:

答案 0 :(得分:11)

  1. 对于左连接 - 我建议使用from whereDefaultIfEmpty

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

  3.   

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

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

     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,
            };