2017-07-03 84 views
-1

我有三個表:購買(RecordEntered如A) LEFT JOIN三個表和SUM在LINQ

  • 產品在國內出售(SoldInCountry如B)
  • 產品出售國以外

    • 產品(SoldOutCountry如C)

    enter image description here

    所述的每個記錄可以是:

    • 進入,僅在國內尚未出售
    • 進入和銷售
    • 進入並僅售出了
    • 進入,並在國內銷售,也是該國以外的國家的

    我開始將表B中的部分分組,如下所示:

    SELECT   
    A.IdRecord, A.Qty, sum(isnull(B.Qty,0)) AS Expr1 
    FROM    
    RecordEntered AS A 
    LEFT OUTER JOIN 
    SoldInCountry AS B ON A.IdRecord = B.IdRecord 
    group by A.IdRecord, A.Qty 
    

    但我不知道如何繼續。

    我想要一個查詢,告訴我有多少件我仍然有現貨。 像這樣:

    A.Qty - (SUM(ISNULL(B.Qty, 0)) + SUM(ISNULL(C.Qty, 0))) 
    

    我在SQL寫了一個例子,但我們的目標是LINQ:

    from a in _ctx..... 
        where ..... 
        select... 
    

    感謝

  • 回答

    1

    這是不容易做到完全外部聯接在LINQ(看到我的答案在這裏:https://stackoverflow.com/a/43669055/2557128),但你並不需要,要解決這個問題:

    var numInStock = from item in RecordEntered 
          select new { 
           item.Code, 
           Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).SingleOrDefault() - 
          (from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).SingleOrDefault() 
          }; 
    

    我以爲只會有一個項目每種類型的一個銷售的記錄,如果有可能不止一個,你需要Sum匹配的記錄:

    var numInStock = from item in RecordEntered 
          select new { 
           item.Code, 
           Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).DefaultIfEmpty().Sum() - 
          (from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).DefaultIfEmpty().Sum() 
          }; 
    
    +0

    哇..第二個代碼是完美的.. TKS – user2080358