Skip to main content
 首页 » 编程设计

c#之如何使用 linq to entities 对所有按月记录求和

2024年02月13日13虾米姐

我的 table 是这样的 表:

id  no.of sales    datetime  
1    14            2013-09-10 
2    45            2013-09-09 
3    18            2013-09-08 
4    14            2013-08-12 
5    15            2013-08-14 
6    18            2013-07-12 

在上表中,第 9 个月有 3 行。第 8 个月有 2 条记录。我需要第 9 个月和第 8 个月所有销售额的总和,依此类推。 有人能告诉我如何实现这一目标吗? 我的查询:

DateTime frommonth = DateTime.Now.AddMonths(-3); 
DateTime tomonth = DateTime.Now; 
var result= from pa in cxt.Products 
            where (pa.datevalue >= frommonth && pa.datevalue < tomonth) 
                && pa.productname == productname 
            orderby pa.datevalue descending 
            select new { noofsales=pa.No_of_sales ,datetime=pa.datevalue}; 

通过使用上面的查询,我得到了第 9 个月的个人记录。我不想要个人的销售额,我需要所有第 9 个月销售额、第 8 个月销售额的总和等等。请告诉我......

请您参考如下方法:

您可以使用 SqlFunctions.DatePart静态方法,将被翻译成DATEPART sql函数:

var results = from r in ctx.Products 
              let year = SqlFunctions.DatePart("yy", r.datevalue) 
              let month = SqlFunctions.DatePart("mm", r.datevalue) 
              where (r.datevalue >= frommonth && r.datevalue < tomonth) 
              group r by new { year, month } into g 
              select new { 
                  Year = g.Key.year, 
                  Month = g.Key.month, 
                  NoSales = g.Sum(x => x.No_of_sales) 
              };