我正在使用Entity Framework
。
表格A
包含id
,someInt
,someDateTime
列。
例如:
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
中进行?我应该如何进行这样的查询?
答案 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()
};