gpt4 book ai didi

linq-to-sql - 具有多个连接、分组依据和计数的 LINQ to SQL

转载 作者:行者123 更新时间:2023-12-04 03:00:28 24 4
gpt4 key购买 nike

我有 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
我在正确的轨道上吗?我需要怎么做才能得到这两个计数?

最佳答案

  • 对于左连接 - 我建议使用 fromwhere和一个 DefaultIfEmpty
  • 您需要使用匿名类型进行分组才能对多个参数进行分组

  • Value cannot be null. Parameter name: inner



    任何连接属性都可以为空吗?
     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,
    };

    关于linq-to-sql - 具有多个连接、分组依据和计数的 LINQ to SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11583799/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com