0

我需要比较上周和两周前用户的分数。

我有一张这样的桌子

user   score  subject       date        
 2      10     math       21/10/2012
 2       5     science    23/10/2012
 2       5     math       16/10/2012
 2       9     science    15/12/2012

我需要生成一个查询,显示上周的分数以及它是否比 2 周前的分数增加或减少

user   score    subject     date         increase/decrease
 2       10      math     21/10/2012       +5
 2       10      science  23/10/2012       -4

日期列不需要包含在查询中我已经有代码来获取从上周到两周前的周范围。但是,我无法比较这两个日期。

DateTime date = DateTime.Now;
DateTime startOneWeekAgo = date.AddDays(-7).Date.AddDays(-(int)date.DayOfWeek),
         endOneWeekAgo = startOneWeekAgo.AddDays(7);

DateTime startTwoWeeksAgo = startOneWeekAgo.AddDays(-7),
         endTwoWeeksAgo = endOneWeekAgo.AddDays(-7);

from s in Scores where s.scoredate >= startOneWeekAgo && s.scoredate < endOneWeekAgo

这导致。这就是我到目前为止所拥有的。帮助将不胜感激。

user score subject
2     10    math
2     5     science
4

1 回答 1

1
DateTime beginningOfWeek = DateTime.Now.BeginningOfWeek();
DateTime twoWeeksAgo = beginningOfWeek.AddDays(-14);
DateTime endOfLastWeek = beginningOfWeek.AddMilliseconds(-1);

var query = from s in scores
            where s.Date >= twoWeeksAgo && s.Date <= endOfLastWeek
            orderby s.Date
            group s by new { s.User, s.Subject } into g
            select new
                {
                    User = g.Key.User,
                    Subject = g.Key.Subject,
                    Date = g.Last().Date,
                    Diff = g.Last().Score - g.First().Score
                };

因此,您总是只选择最后两个分数(两周前和一周前),每组中只有两条记录。

如果数据库中只有一周的结果,那么差异将为零,因为组中的最后一个条目和第一个条目将是相同的。

您也可以使用一些DateTime扩展来获得一周的开始:

public static class DateExtensions
{
    public static DateTime BeginningOfWeek(this DateTime date, 
                           DayOfWeek firstDayOfWeek = DayOfWeek.Monday)
    {
        if (date.DayOfWeek == firstDayOfWeek)
            return date.Date;

        DateTime result = date.AddDays(-1);

        while (result.DayOfWeek != firstDayOfWeek)
            result = result.AddDays(-1);

        return result.Date;
    }
}

还有一件事 - 尽量避免一次声明多个变量。

于 2012-10-30T17:07:08.480 回答