1

Currently I have SQL query like

 select tt.userId, count(tt.userId) from (SELECT userId,COUNT(userId) as cou
  FROM [dbo].[users]

  where createdTime> DATEADD(wk,-1,GETDATE())

   group by userId,DATEPART(minute,createdTime)/5) tt group by tt.userId

Now I have the Data in the Data Table, I need to convert the above the query to LINQ and execute against the data table. I am unable to do so , can anybody help me out.

This is what query does, It groups the users into 5 minutes time slots and then counts the number of timeslots per user.

Note : I am not able to use Linqer to create the Linq queries because this table does not exist in the database, it's a virtual one created dynamically.

Midhun Murali
  • 2,089
  • 6
  • 28
  • 49

3 Answers3

2

Bit complex query, giving my best to make it work.

var result = table.AsEnumerable().Where(u=> u.Field<DateTime>("createdTime") > DateTime.Now.AddDays(-7)) //subtract a week
        .GroupBy(g=> new { userid = g.Field<string>("userId") , span = g.Field<DateTime>("createdTime").Minute })
        .Select(g=> new { userid = g.Key.userid, count = g.Count()})
        .GroupBy(g=> g.userid ).Select(s=> new {userid = s.Key, count = s.Count()}); 

Working Demo

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
1

This SQL can be rewritten like this

SELECT
  COUNT(U.UserId),
  U.[createdTime]
FROM USERS U WHERE createdTime> DATEADD(wk,-1,GETDATE())
GROUP BY U.UserId,
         DATEPART(MONTH, U.[createdTime]),
         DATEPART(DAY, U.[createdTime]),
         DATEPART(HOUR, U.[createdTime]),
         (DATEPART(MINUTE, U.[createdTime]) / 5)

And its corresponding Linq for DataTable would be

var users =  myDataTable.AsEnumerable()
                .Select(r=> new {
                    UserId = r.Field<int>("UserId"),
                    CreatedTime = r.Field<DateTime>("createdTime")
                }).ToList();
            var groupedUsersResult = from user in users where user.CreatedTime > user.CreatedTime.AddDays(-7) group user by 
                                   new {user.CreatedTime.Year,user.CreatedTime.Month,user.CreatedTime.Day,Minute=(user.CreatedTime.Minute/5),user.UserId}
                                   into groupedUsers select groupedUsers;

Fiddle is here

Subin Jacob
  • 4,692
  • 10
  • 37
  • 69
0

I will suggest to use LINQPad4. It would be easy to do that and that will help you a lot in writing LINQ queries. https://www.linqpad.net/

Sagar
  • 272
  • 1
  • 4
  • 13