1

给定这样的表:

UserID,DateOfEntry,TimeWorked,Status
user1,2013-04-23,5,Submitted
user1,2013-04-22,7,Submitted
user1,2013-04-29,11,Submitted
user1,2013-04-24,3,Approved
user2,2013-04-22,9,Submitted

我将如何获得这个结果集:

UserID,WeekStart,SumTimeWorked
user1, 2013-04-21, 12
user1, 2013-04-28, 11
user2, 2013-04-21, 9

分组基于用户 ID 和“DateOfEntry”中日期之前的星期日?

如果可能的话,我更喜欢 Lambda 语法。

编辑 这是基于托马斯回答的工作查询。这是我正在查询的实际表的实际查询,因此它可能与上面的示例不完全匹配。

var entries = _db.TimeEntries.GroupBy(g => new {
weekstart = g.DateOfEntry.AddDays(-(int)g.DateOfEntry.DayOfWeek),
userID = g.UserID
})
.OrderBy(c => c.Key.userID)
.Select(c => new {
userID = c.Key.userID,
weekStart = c.Key.weekstart,
Duration = c.Sum(sub => sub.Duration)
});

编辑 2 上面的查询在 LINQPad 中工作,它使用的实际代码直到今天才准备好进行测试 - 不幸的是,在 LINQPad 中我使用的是 LINQ to SQL,而在代码中我们使用的是 LINQ to Entities。我现在收到此错误,如果有人有任何想法...

LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)'
method, and this method cannot be translated into a store expression.

编辑 3 好的,我想我已经弄清楚了。我不得不添加两个 Using 语句:

using System.Data.Objects;
using System.Data.Objects.SqlClient;

然后将查询更改为:

var entries = _db.TimeEntries.GroupBy(g => new {
weekstart = EntityFunctions.AddDays(g.DateOfEntry, -SqlFunctions.DatePart("weekday", g.DateOfEntry)),
userID = g.UserID
})
.OrderBy(c => c.Key.userID)
.Select(c => new {
userID = c.Key.userID,
weekStart = c.Key.weekstart,
Duration = c.Sum(sub => sub.Duration)
});

资料来源:Linq to EntityFramework DateTimeLINQ to Entities Join on DateTime.DayOfWeek

4

1 回答 1

1

linq 查询实际上非常简单:

var q = from s in submissions
        group s by GetKey(s) into g
        select new
        {
            UserId = g.Key.Key,
            WeekStart = g.Key.Value,
            SumTimeWorked = g.Sum(sub => sub.TimeWorked)
        };

诀窍是定义适当的分组方法。这个使用KeyValuePairs只是因为我不想在这个答案中加入类定义:

private KeyValuePair<string, DateTime> GetKey(Submission s)
{
    return new KeyValuePair<string, DateTime>
            (s.UserID, s.DateOfEntry.AddDays(-(int)s.DateOfEntry.DayOfWeek));
}

顺便说一句,运行它后,我注意到您的其中一行在SumTimeWorked列中有错误的值。它应该是:

user1, 2013-04-21, 15
于 2013-04-23T22:40:10.743 回答