2015-12-28 106 views
2

我無法從linq查詢中獲取分組總和。我試圖在某個日期範圍內獲得產品的淨變化。現在,我的查詢運行並返回每個事務的總數量更改,但我無法獲得總和。我的查詢是這樣的:使用LINQ for Group和Sum

from t in Transactions 
join p in Products on t.Product.ID equals p.ID 
where t.TransactionDate >= DateTime.Parse("12/01/2015") && t.TransactionDate <= DateTime.Parse("12/31/2015") 
orderby p.ProductCode 
select new 
{ 
    Product = p.ProductCode, 
    Description = p.Description, 
    TotalQuantityChanged = (t.TransactionType.AddRemove == "Addition" ? (t.FullQuantity + (t.PartialQuantity/p.Pieces)).ToString() : (-1 * (t.FullQuantity + (t.PartialQuantity/p.Pieces))).ToString()) 
} 

這將返回

Product  Description       TotalQuantityChanged 

B107  3 ½" x 11" x 105" Kraft Faced R-11   23 
B107  3 ½" x 11" x 105" Kraft Faced R-11   -16 
X13AK  3 ½" x 11" x 105" Kraft Faced R-13   65 
X13AK  3 ½" x 11" x 105" Kraft Faced R-13   45 
X13AK  3 ½" x 11" x 105" Kraft Faced R-13   -12 
X45EX  3 ½" x 15" x 105" Kraft Faced R-15 HD  3 
X45EX  3 ½" x 15" x 105" Kraft Faced R-15 HD  36 
X45EX  3 ½" x 15" x 105" Kraft Faced R-15 HD  -7 

,但我已經試過組的所有方式,並沒有運氣總結。這是結果應該是什麼樣子:

Product  Description       TotalQuantityChanged 

B107  3 ½" x 11" x 105" Kraft Faced R-11   7 
X13AK  3 ½" x 11" x 105" Kraft Faced R-13   98 
X45EX  3 ½" x 15" x 105" Kraft Faced R-15 HD  32 

我已經試過這樣的分組,但我在where子句,在我的SELECT語句中得到一個錯誤。我不知道如何分組或獲得總和。任何援助將不勝感激。

+0

什麼是你的錯誤? – Minh

+0

爲什麼一切都是字符串?少字符串更多類型! – Hogan

回答

2

這大約是你要什麼:

from t in Transactions 
join p in Products on t.Product.ID equals p.ID 
where t.TransactionDate >= DateTime.Parse("12/01/2015") && t.TransactionDate <= DateTime.Parse("12/31/2015") 
group t.TransactionType.AddRemove == "Addition" 
      ? t.FullQuantity + (t.PartialQuantity/p.Pieces) 
      : -1 * (t.FullQuantity + (t.PartialQuantity/p.Pieces)) 
    by new {p.ProductCode, p.Description} into g 
select new 
{ 
    Product = g.Key.ProductCode, 
    Description = g.Key.Description, 
    TotalQuantityChanged = g.Sum().ToString() 
} 
+0

感謝@StriplingWarrior,使用它我能夠使查詢工作。 – mack