c# - summing values of a column based on id -
i have table keeps track of users online time. e.g. if user logs in @ 10:00 , leaves @ 10:30 1 record userid, login-time, logout-time , date. user comes again @ 11:05 , goes @ 11:50.that record. want sum of time each user each day. using entity-frame work, c#, here data structure
id userid logintime logouttime date
1 1 10:00 10:20 11-06-2015
1 1 10:30 10:50 11-06-2015
1 1 09:00 10:00 12-06-2015
1 1 10:15 11:00 12-06-2015
output
for 11-06-2015 should 40 minutes
12-06-2015 should 105
first, created single table database mimic data structure:
static void createandseeddatabase() { context context = new context(); timetracker entry1 = new timetracker() { userid = 1, logintime = new datetime(2000, 1, 1, 0, 0, 0), logouttime = new datetime(2000, 1, 1, 1, 0, 0) }; timetracker entry2 = new timetracker() { userid = 1, logintime = new datetime(2000, 1, 1, 1, 0, 0), logouttime = new datetime(2000, 1, 1, 2, 0, 0) }; timetracker entry3 = new timetracker() { userid = 1, logintime = new datetime(2000, 1, 2, 0, 0, 0), logouttime = new datetime(2000, 1, 2, 2, 0, 0) }; timetracker entry4 = new timetracker() { userid = 2, logintime = new datetime(2000, 1, 1, 0, 0, 0), logouttime = new datetime(2000, 1, 1, 1, 0, 0) }; list<timetracker> entrylist = new list<timetracker>() { entry1, entry2, entry3, entry4 }; context.timetrackers.addrange(entrylist); context.savechanges(); } class context : dbcontext { public context() { database.setinitializer(new createdatabaseifnotexists<context>()); database.initialize(true); } public dbset<timetracker> timetrackers { get; set; } } public class timetracker { public int timetrackerid { get; set; } public int userid { get; set; } public datetime logintime { get; set; } public datetime logouttime { get; set; } }
the following picture shows results within sql server:
next, created following stored procedure:
create procedure groupbyuseranddate begin select timetracker.userid, cast(timetracker.logouttime date) logoutdate, sum(datediff(second, timetracker.logintime, timetracker.logouttime)) timesum [ef_6_code_first_database_table_not_create.context].[dbo].[timetrackers] timetracker group timetracker.userid, cast(timetracker.logouttime date) end
this produces following results:
lastly, call stored procedure using entityframework:
static void executestoredprocedure() { context context = new context(); queryresult[] results = context.database.sqlquery<queryresult>("dbo.groupbyuseranddate").toarray(); } public class queryresult { public int userid { get; set; } public datetime logoutdate { get; set; } public int timesum { get; set; } }
Comments
Post a Comment