2014-02-13 208 views
0

我已經在這裏工作了一段時間,所以我想我會在這裏發佈,看看是否有人有任何想法如何查詢可以轉換爲LINQ。LINQ查詢加入,分組和sum()

這裏是MySQL查詢:

SELECT SUM(line_ord.itemqty) AS LineOrderQTY, SUM(assemblyNumber.qty) AS 
AssemblyQTY FROM line_ord 
LEFT JOIN 
(
    SELECT sum(assemblyno.qty) AS qty, assemblyno.row_id FROM assemblyno 
    INNER JOIN line_ord ON assemblyno.row_id = line_ord.row_id 
    WHERE line_ord.bdnum = 'S61460' 
) AS assemblyNumber ON line_ord.row_id = assemblyNumber.row_id 
WHERE line_ord.bdnum = 'S61460' 

這是我迄今爲止的LINQ查詢,但它不返回正確的結果。

var items = (from c in Context.OrderLineItemData 
     join e in Context.AssemblyLabelData on c.ID equals e.RowID 
        where c.BreakdownNumber == breakdownNumber 

        group c by c.BreakdownNumber into g 
        select new 
        {        
          AssemblyQuantity= g.Sum(x => x.Quantity), 
          LineOrdQuantity = g.Sum(**WHAT GOES HERE?**) 
        }).FirstOrDefault() 

我確實設法讓它像這樣工作,但對我來說似乎有點混亂。

  var items = (from c in Context.OrderLineItemData 
        join e in Context.AssemblyLabelData on c.ID equals e.RowID 
        where c.BreakdownNumber == breakdownNumber 

        group c by c into g 
        select new 
        {        
          AssemblyQuantity= g.Sum(x => x.Quantity), 
          LineOrdQuantity = (from e in Context.OrderLineItemData where e.BreakdownNumber == breakdownNumber select e.Quantity).Sum() 
        }).FirstOrDefault(); 

有沒有更好的方法來做到這一點?

回答

0

得到了我的答案。看起來像查詢對象必須被創建,然後我可以使用它來執行我的計算。

var items = (from od in Context.OrderLineItemData 
      join ad in Context.AssemblyLabelData on od.ID equals ad.RowID into odGroup 
      from g in odGroup.DefaultIfEmpty() 
      where od.BreakdownNumber == breakdownNumber 
      group g by new 
      { 
        breakdown = od.BreakdownNumber, 
        LineOrd = od, 
        AssemblyQty = g == null ? 0 : g.Quantity 
      } 
      into groupped 
      select new 
      { 
        Breakdown = groupped.Key.breakdown, 
        AssemblyQty = groupped.Sum(x => x.Quantity), 
        lineOrdQty = groupped.Key.LineOrd.Quantity 
      } 
     );    
     int remainingQuantity = items.Sum(x => x.lineOrdQty) - items.Sum(x => x.AssemblyQty);