按月分组

时间:2017-03-06 20:14:46

标签: asp.net .net asp.net-mvc entity-framework entity-framework-4

我正在尝试返回有多少客户注册的结果'一个月内。目前它返回每个特定日期的计数。见下文:

Count for customers enrolled per day

以下是我的控制器中的代码:

 public ActionResult About()
        {
            IQueryable<EnrollmentDateGroup> data = from customer in db.Customers
                                                   group customer by customer.EnrollmentDate  into dateGroup

                                                   select new EnrollmentDateGroup()
                                                   {
                                                       EnrollmentDate = dateGroup.Key,
                                                       CustomerCount = dateGroup.Count() 

        };

任何人都可以建议我如何计算每月注册的客户数量?

提前致谢。

更新

使用时出现以下错误:

group customer by new { customer.EnrollmentDate.Year, customer.EnrollmentDate.Month } into dateGroup

enter image description here

3 个答案:

答案 0 :(得分:1)

您需要按月份和年份进行分组。当您通过完整日期时,它包含一个会使分组陷入混乱的日期组件。例如:

group customer by new { Year = customer.EnrollmentDate.Year, Month = customer.EnrollmentDate.Month }

<强>更新

那是因为您想要将密钥直接设置为EnrollmentDate属性,密钥现在是匿名类型,而不是DateTime。要么创建DateTime,要么做不同的事情。

EnrollmentDate = new DateTime(m.Key.Year, m.Key.Month, 1),

答案 1 :(得分:0)

在GROUPBY子句中使用强制转换

GROUP BY CAST(月份(日期)AS VARCHAR(2))+&#39; - &#39; + CAST(年(日期)AS VARCHAR(4))

答案 2 :(得分:0)

试试这个。

var result = from s in data
             group s by new { date = new DateTime(s.EnrollmentDate.Year, s.EnrollmentDate.Month, 1)} into g 
select new {
date = g.Key.date,
Sum = g.Sum(x=>x.CustomerCount)
};