22

我正在使用以下 LINQ 从表中选择数据:

(from m in entity.Results
where m.Group == 0 ||
m.Group == 1
orderby m.Points descending
select m);

这为我提供了第 1 组或第 2 组中所有用户的结果。这样我就可以显示他们拥有的分数。但这向我展示了他们分别在第 1 组和第 2 组中的分数。

我如何对它们进行分组并显示它们的总分?所以代替这个(我现在拥有的):

user1 - group1 - 10
user1 - group2 - 7
user2 - group1 - 7
user2 - group2 - 5

我要这个:

user1 - total: 17
user2 - total: 12

我如何调整我的查询以获得这样的结果集?

4

4 回答 4

26

您需要对用户进行分组,然后用于Sum计算TotalPoints

from m in entity.Results
where m.Group == 0 || m.Group == 1
group m by m.User into g
let TotalPoints = g.Sum(m => m.Points)
orderby TotalPoints descending
select new { User = g.Key, Username = g.Key.Username, TotalPoints };
于 2012-06-06T11:45:13.987 回答
19
entity.Results
      .Where(m => m.Group == 0 || m.Group == 1)
      .GroupBy(m => m.UserID)
      .Select(m => new { User = m.Key, TotalPoints = m.Sum(v => v.Points) })
      .OrderByDescending(m => m.TotalPoints);
于 2012-06-06T11:45:52.667 回答
2

嗨 Vivendi 使用这个(请根据您的要求编辑)

var q = (from h in entity.Results
group h by new { h.UserID} into hh
select new {
    hh.Key.UserID,
    Score = hh.Sum(s => s.Points )
}).OrderByDescending(i => i.Points);

输出

总数:17

总数:12

于 2012-06-06T11:51:39.450 回答
0

另一个有多个总和和连接的示例

 from e in _context.LearnResults
 join c in _context.Country on e.CountryId equals c.CountryId
 where c.DomainId.Equals("xx")
 group e by e.Country.Name into newCountry
 let Approved = newCountry.Sum(e => e.Approved)
 let Total = newCountry.Sum(e => e.Total)
 select new LearnResults() { CountryName = newCountry.Key, Approved= Approved, Total=Total };
于 2017-06-14T16:24:39.487 回答