按某些值和时间段分组

时间:2014-03-11 11:38:50

标签: sql entity-framework group-by aggregate-functions

我正在使用Entity Framework

表格A包含idsomeIntsomeDateTime列。

例如:

id | someInt | someDateTime
 1 |     2   | 2014-03-11
 2 |     2   | 2013-01-01
 3 |     2   | 2013-01-02
 4 |     1   | 2014-03-05
 5 |     1   | 2014-03-06

现在我想采取一些统计信息:每个someInt值,我想知道有多少行不超过24h年,1 week年,1 month旧。从上面的值我会得到:

someInt | 24h | 1 week | 1 month | any time
    1   |  0  |    2   |     2   |     2
    2   |  1  |    1   |     1   |     3

是否可以在SQL中进行,如果可以,可以在Entity Framework中进行?我应该如何进行这样的查询?

1 个答案:

答案 0 :(得分:2)

someInt分组记录,然后进行子查询以获取您感兴趣的每个时间段的行数:

DateTime now = DateTime.Now;
DateTime yesterday = now.AddDays(-1);
DateTime weekAgo = now.AddDays(-7);
DateTime monthAgo = now.AddDays(-30); // just assume you need 30 days
DateTime yearAgo = new DateTime(now.Year - 1, now.Month, now.Day);

var query = from a in db.A
            group a by a.someInt into g
            select new {
               someInt = g.Key,
               lastDay = g.Count(a => a.someDateTime >= yesterday),
               lastWeek = g.Count(a => a.someDateTime >= weekAgo),
               lastMonth = g.Count(a => a.someDateTime >= monthAgo),
               lastYear = g.Count(a => a.someDateTime >= yearAgo),
               anyTime = g.Count()
            };