代码之家  ›  专栏  ›  技术社区  ›  Clyde

多个表中的LINQ聚合

  •  1
  • Clyde  · 技术社区  · 16 年前

    SELECT A.Recruiter, SUM(O.SaleAmount * I.Commission)  --This sum from fields in two different tables is what I don't know how to replicate
    FROM Orders AS O
    INNER JOIN Affiliate A ON O.AffiliateID = A.AffiliateID
    INNER JOIN Items AS I ON O.ItemID = I.ItemID
    GROUP BY A.Recruiter
    

    我已经做到了:

    from order in ctx.Orders
    join item in ctx.Items on order.ItemI == item.ItemID
    join affiliate in ctx.Affiliates on order.AffiliateID == affiliate.AffiliateID
    group order  //can I only group one table here?
      by affiliate.Recruiter into mygroup
    select new { Recruiter = mygroup.Key, Commission = mygroup.Sum(record => record.SaleAmount * ?????) };
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   Amy B    16 年前
    group new {order, item} by affiliate.Recruiter into mygroup 
    select new {
      Recruiter = mygroup.Key,
      Commission = mygroup
        .Sum(x => x.order.SaleAmount * x.item.Commission)
    }; 
    

    以及另一种编写查询的方法:

    from aff in ctx.Affiliates
    where aff.orders.Any(order => order.Items.Any())
    select new {
      Recruiter = aff.Recruiter,
      Commission = (
        from order in aff.orders
        from item in order.Items
        select item.Commission * order.SaleAmount
        ).Sum()
    };
    
        2
  •  1
  •   Numan    16 年前

    试试linqpad,谷歌,神奇的工具!