Question

I'm using Entity Framework.

There is table A with columns id, someInt, someDateTime.

For example:

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

Now I want to take some statistics: per each someInt value I want to know how many rows are not more than i.e. 24h old, 1 week old, 1 month old. From values above I would get:

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

Is it possible in SQL and if so is it possible in Entity Framework? How should I make queries like this?

Was it helpful?

Solution

Group records by someInt and then make sub-queries to get number of rows for each period of time you are interested in:

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()
            };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top