【问题标题】:Group count by month按月分组计数
【发布时间】:2017-07-26 20:38:36
【问题描述】:

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

这是我的控制器中的代码:

 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

【问题讨论】:

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

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


【解决方案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),

【讨论】:

    【解决方案2】:

    在 GROUPBY 子句中使用强制转换

    GROUP BY CAST(MONTH(date) AS VARCHAR(2)) + '-' + CAST(YEAR(date) AS VARCHAR(4))

    【讨论】:

    • 这只适用于实际的SQL。这里的 OP 使用的是 LINQ to SQL,这是一个不同的野兽。
    【解决方案3】:

    试试这个。

    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)
    };
    

    【讨论】:

    • 我不确定您是否可以按新的DateTime 分组,因为它在技术上是不同的对象实例,但显然 group by 可以弥补这一点。但是,此时,无需将其包装在匿名对象中。就做group s by new DateTime(s.EnrollmentDate.Year, s.EnrollmentDate.Month, 1)
    猜你喜欢
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2021-11-08
    • 2017-03-25
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    相关资源
    最近更新 更多