繁体   English   中英

如何使用linq对实体的所有月份明智记录求和?

[英]How to sum all the month wise records using linq to entities?

我的表像这样的表:

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个月有三排。第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)
              };
var result = from r in cxt.Products
             group r by r.datevalue.Month
             into g
             select new {Month = g.Key, Sum = g.Sum(p=>p.No_of_sales)};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM