Multiple group by and Sum LINQ

后端 未结 4 1882
心在旅途
心在旅途 2020-12-29 07:02

I have a products sales table that looks like this:

saleDate     prod        qty
10/22/09     soap        10
09/22/09     pills       05
09/25/09     soap            


        
4条回答
  •  甜味超标
    2020-12-29 07:25

    Sure.

    It'll look like this:

    var GroupedSales = 
          from p in products 
          group p by p.saleDate.Month into g 
          select new { saleMonth = g.saleDate.Month, QtySold = g.Sum(p => p.qty) }; 
    

    See: http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped

    Also, note that I was operating under the assumption that your dataset only had 2009 data. If you want to group by month/year, you can use saleDate.ToString("yyyyMM") instead of saleDate.Month.

提交回复
热议问题