根据id对列的值求和

时间:2016-05-25 06:12:48

标签: c# sql-server entity-framework

我有一张表可以跟踪用户在线时间。例如如果用户在10:00登录并在10:30离开,那将是一条带有userId,登录时间,登出时间和日期的记录。用户在11:05再次来到11:50。这是另一个记录。我想要每个用户每天的时间总和。使用实体框架工作,c#, 这是数据结构

id userId loginTime logoutTime日期
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
她是输出

2015年6月11日应该是40分钟 对于12-06-2015,应该是105

1 个答案:

答案 0 :(得分:0)

首先,我创建了一个表模拟数据结构的表数据库:

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; }
}

下图显示了SQL Server中的结果:

Data Setup

接下来,我创建了以下存储过程:

CREATE PROCEDURE GroupByUserAndDate
AS
BEGIN
    SELECT TimeTracker.UserId, CAST(TimeTracker.LogoutTime AS date) AS LogoutDate,  SUM(DATEDIFF(SECOND, TimeTracker.LoginTime, TimeTracker.LogoutTime)) AS TimeSum
    FROM [ef_6_code_first_database_table_not_create.Context].[dbo].[TimeTrackers] AS TimeTracker
    GROUP BY TimeTracker.UserId, CAST(TimeTracker.LogoutTime AS date)
END

这会产生以下结果:

Stored Procedure Results

最后,我使用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; }
}