2016-03-20 58 views
0

我有每個產品發佈計劃的數據表: enter image description here如何使用linq計算每個季度每個產品的總金額?

我想計算量總和使用LINQ在每一個季度的每一件單品。在SQL我會用: enter image description here

我怎麼能在linq做到這一點? 我試過這段代碼:

public List<ValuePairPlanned> GetQuantityOfEachProductPlannedForRelease(int departmentId) 
    { 
     var amountByProducts = (from rp in _context.ReleasePlans 
           join p in _context.Products 
            on rp.ProductProductId equals p.ProductId 
           where rp.DepartmentDepartmentId == departmentId 
           group new { rp, p } by new { rp.ProductProductId, p.ProductId, p.ProductName, rp.DateTime, rp.Amount } 
     into grp 
           select new 
           { 
            grp.Key.ProductName, 
            grp.Key.DateTime, 
            PlannedAmount = grp.Sum(g => g.rp.Amount) 
           }).Distinct().ToList().ConvertAll(x => new ValuePairPlanned() 
           { PlannedAmount = x.PlannedAmount, Quarter = (x.DateTime.AddDays(2).Month - 1)/3 + 1, ProductName = x.ProductName }); 

     return amountByProducts; 
    } 

enter image description here

但作爲一個結果,我爲每一個產品,每季度量值。我該如何解決它?謝謝你的幫助。

+0

的'Dintinct'不起作用,因爲 'PlannedAmount' 是dirrferent。 – MichaelMao

+0

對於這個愚蠢的問題,我很抱歉,但是你的意思是? – Eluvium

+0

這是什麼類型的LINQ?到SQL?實體? –

回答

0

由於您使用的是實體框架,請查看DbFunctions,以便您可以在SQL Server上執行日期添加。如果您不使用DbFunctions,那麼您必須先通過ToList()獲取您的連接表,然後執行數據運算來計算季度。

下面應該讓你非常接近:

var amountByProducts = from p in _context.Products 
      join rp in _context.ReleasePlans 
      on p.ProductId equals rp.ProductId 
      where rp.DepartmentDepartmentId == departmentId 
      group new 
      { 
       p.ProductName, 
       Quarter = (DbFunctions.AddDays(rp.DateTime,2).Month - 1)/3 + 1, 
       rp.Amount 
      } 
      // group all product plans in a given quarter 
      by new 
      { 
       p.ProductName, // shouldn't this be ProductId? 
       Quarter = (DbFunctions.AddDays(rp.DateTime,2).Month - 1)/3 + 1 
      } 
      into grp 
      // from the grouped entries, sum the amounts 
      select new ValuePairPlanned() 
      { 
       PlannedAmount = grp.Sum(g => g.Amount), 
       Quarter = grp.Key.Quarter, 
       ProductName = grp.Key.ProductName 
      }; 

return amountByProducts.ToList(); 
+0

是的,多數民衆贊成在!謝謝!是否最好使用DbFunctions而不是在查詢中計算? – Eluvium

+1

使用您的原始代碼,您使用查詢('ToList()')將所有記錄拉下來,進行計算,然後爲程序的其餘部分提供結果。通過使用'DbFunctions',這可以避免從SQL服務器中關閉任何數據(因爲服務器上正在發生的所有事情),直到您計算出所有結果。由於您將更少的記錄從服務器傳回,因此它具有更好的性能。事實上,如果您處理大量記錄,這會產生較大的影響。 –