0

我試圖返回一個月內有多少客戶「註冊」的結果。目前它返回每個特定日期的計數。見下圖:按月計算的組數

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() 

     }; 

任何人都可以建議我如何能有多少客戶每月招收的計數?

在此先感謝。

UPDATE

我收到以下錯誤,當我使用:

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

enter image description here

+0

'通過新的集團客戶{customer.EnrollmentDate.Year,customer.EnrollmentDate.Month}' –

回答

1

你需要按月份和年份,獨自一人。當你通過完整的日期時,它會包含一個將會搞亂分組的日子組件。例如:

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

UPDATE

那是因爲你綁直接設置關鍵看你EnrollmentDate屬性格式,現在的關鍵是一個匿名類型,而不是一個DateTime。創建一個DateTime或者做一些不同的事情。

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

使用您的GROUPBY子句中鑄造

GROUP BY CAST(MONTH(日期)AS VARCHAR(2))+ ' - ' + CAST(YEAR(日期)爲varchar(4))

+0

這僅適用於使用實際的SQL。這裏的OP使用LINQ to SQL,這是一個不同的野獸。 –

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

我不確定你是否可以通過新的'DateTime'進行分組,因爲它在技術上是不同的對象實例,但顯然可以通過分組來彌補這一點。但是,在這一點上,不需要將其包裝在匿名對象中。只要按新的日期時間進行分組(s.EnrollmentDate.Year,s.EnrollmentDate.Month,1)' –