3

我有以下表格,其中包含 ActivityLog 的记录:

ID, UserId,      Category,   Created
1       11     DeAssigned    05/10/2012
2       11          LogIn    05/11/2012
3       20       Assigned    06/15/2012
4       11       Assigned    06/10/2012
5       20     DeAssigned    06/13/2012
6       20       Assigned    07/12/2012
7       11     DeAssigned    07/16/2012
8       20       Assigned    08/15/2012
...

现在我查询表以创建相同的结构相同的结果,例如

var data = new[] { 
                    new { Month = "05", Assigned = 14, DeAssigned = 5, LogIn=1 },
                    new { Month = "06", Assigned = 5, DeAssigned = 2, LogIn=0 },
                    new { Month = "07", Assigned = 50, DeAssigned = 8, LogIn=0 },
                    new { Month = "08", Assigned = 15, DeAssigned = 1, LogIn=0 }
};

我所取得的成就:

var result = (from l in repoA.GetAll()
                      where   l.Created >= System.DateTime.Now.AddYears(-1)
                      group l by new { l.Created.Value.Month, l.Category }
                      into groups
                      orderby  groups.Key.Month 
                      select new
                                 {
                                     Month = groups.Key.Month,
                                     Category = groups.Key.Category,
                                     Count = groups.Count()
                                 });

没有最佳结果,但计算按月份分组的所有活动:

 [0] {Month = 6, Category = Assigned, Count = 2}
 [0] {Month = 6, Category = Designed, Count = 1}
 [0] {Month = 6, Category = LogIn, Count = 1}
 [0] {Month = 7, Category = Assigned, Count = 3}

如何查询我的表格以将我的结果格式化为“水平计数”格式?

4

1 回答 1

2

或者更简单:

var result = (from l in repoA.GetAll()
                           where   l.Created >= System.DateTime.Now.AddYears(-1) 
                           group l by l.Created.Month into groups
                           orderby groups.Key ascending
                           select new
                              {
                                  Month = groups.Key,
                                  Assigned = groups.Where(g => g.Category == "Assigned").Count(),
                                  Deassigned = groups.Where(g => g.Category == "DeAssigned").Count(),
                                  LogIn = groups.Where(g => g.Category == "LogIn").Count()
                              });
于 2012-06-29T10:19:08.127 回答