从Total LINQ Query获得排名

时间:2015-09-11 15:34:30

标签: sql asp.net-mvc linq-to-entities entity-framework-6

我有两张桌子。首先是比赛用户和比赛点。 表与ParticipateID之间存在外键关系。 在CompetitionPoints表中,有多个参与点的不同点数。所以我想根据总积分获取总积分和等级。因此,如果一个参与ID有多个相同的总积分,那个参与者的等级应该相同。它相同喜欢该学生的总分和成绩。 这是我的代码。

var competitionusers = (from c in db.CompetitionUsers
group c by new { c.ParicipateId, c.CompetitionPoints.FirstOrDefault().Points }                                     
  into g orderby g.Key.Points descending select 
  new { Points = db.CompetitionPoints.Where
          (x => x.ParticiapteId == g.FirstOrDefault().ParicipateId).Sum(x => x.Points),   

Rank = (from o in db.CompetitionUsers 
   group o by o.CompetitionPoints.FirstOrDefault().Points into l                                                  
  select l).Count(s => s.Key > db.CompetitionPoints.
   Where(x => x.ParticiapteId == g.FirstOrDefault().ParicipateId).Sum(x => x.Points)) + 1,  
}).Where(x => x.Points != null).OrderByDescending(x => x.Points).AsQueryable();

2 个答案:

答案 0 :(得分:0)

如果我正确理解您的数据模型,我认为您可以简化为以下内容:

var result = db.CompetitionUsers
    // group by total points
    .GroupBy(cu => cu.CompetitionPoints.Sum(cp => cp.Points)) 
    // order by total points descending
    .OrderByDescending(g => g.Key) 
    // calculate rank based on position in grouped results
    .SelectMany((g, i) => g.Select(cu => new { Rank = i+1, TotalPoints = g.Key, CompetitionUser = cu })); 

答案 1 :(得分:0)

IQueryable<CompetitionLaderMadel> competitionUsers;
            competitionUsers = (from c in db.CompetitionUsers

select new CompetitionLaderMadel                                
{                                    
CompetitionName = c.Competition.CompetitionName,
                 CompetitionId = c.CompetitionId,                                    
                                    Points = db.CompetitionPoints.Where(x => x.ParticiapteId == c.ParicipateId).Sum(x => x.Points),
                                    IsFollow = db.CrowdMember.Any(x => x.Following == userid && x.UserCrowd.UserID == c.UserId && x.Status != Constants.Deleted),

}).Where(x => x.Points != null && x.UserId != null).OrderByDescending(x => x.Points);

然后写了这个查询

var q = from s in competitionUsers
                    orderby s.Points descending
                    select new
                    {
                        CompetitionName = s.CompetitionName,
                        CompetitionId = s.CompetitionId,
                        HeadLine = s.HeadLine,
                        UserId = s.UserId,
                        Points = s.Points,
                        Image = s.Image,
                        IsFollow = s.IsFollow,
                        UserName = s.UserName,
                        Rank = (from o in competitionUsers
                                where o.Points > s.Points
                                select o).Count() + 1
                    };