1

给定以下模型,我希望能够检索单个玩家获得的积分数以及给定时间段内所有玩家获得的平均积分数。这应该在单个数据库查询中完成(我还想要其他统计数据,例如每个团队的平均得分,稍后会出现,但概念应该是相同的)。

度过了糟糕的一天,却一无所获。有人可以帮我吗?

public class Player
{
    public int Id { get; set; }
    public ICollection<PlayerGame> PlayerGames { get; set; }

    ...
}

public class PlayerGame
{
    public int Id { get; set; }

    public int Points { get; set; }

    public int PlayerId { get; set; }
    public Player Player { get; set; }

    public int GameId { get; set; }
    public Game Game { get; set; }

    ...
}

public class Game
{
    public int Id { get; set; }

    ...
}

编辑:

好的。暂时将游戏实体排除在外,并更改您的代码以适应我的回购。这就是我现在所拥有的:

var query = from p in _playerRepository.Query()
                        from pg in p.PlayerGames
                        group new { p, pg } by 1 into ppg
                        select new
                        {
                            SinglePlayerPointsGained = (from x in ppg
                                                        where x.p.Id == playerId && x.pg.Date > startDateTime
                                                        select x.pg.Points).Sum(),
                            AveragePoints = (from x in ppg 
                                             where x.pg.Date > startDateTime
                                             select x.pg.Points).Average(),                            
                        };

所以现在我只需要平均点数计算来考虑在评论中提到的那个时期没有参加过比赛的球员。

4

1 回答 1

0

我假设Game班级有一个DateTime财产。基本思想是使用group by 1技巧

DateTime startDateTime, endDateTime;

int playerId;

var query = from p in context.Players
            join pg in context.Players on p.Id equals pg.PlayerId
            join g in context.Games on pg.GameId equals g.Id               
            group new { p, pg, g } by 1 into ppgg
            select new {
               SinglePlayerPointsGained = (from x in ppgg
                                           where x.p.PlayerId == playerId
                                           where x.g.DateTime >= startDateTime && x.g.DateTime <= endDateTime
                                           select x.pg.Points ).Sum(),
               AveragePoints = (from x in ppgg
                                group x.pg.Points by x.p.PlayerId into g
                                select g.Key).Average()

            };
于 2012-11-06T20:24:49.233 回答