2

几天来我一直在寻找答案,每次我认为我已经接近时,我都会遇到一些障碍。

我有两张表,一张带有players(playerID,Name),一张带有activities(actionID,playerID,Quarter,Score)。我想对join这些表格进行汇总,计算每个球员在每个季度的得分。在输出中,我想查看播放器表(名称)以及活动表(季度)的内容,当然还有总和(分数)。

在 SQL 中,它会是这样的:

SELECT p.Name, a.Quarter, 'TotalScore' = sum(a.Score) 
FROM players p
JOIN activities a on p.playerID = a.playerID
GROUP BY p.Name, a.Quarter

我找到了几个示例,使用 Join 或 Group Join,但我似乎无法从子表中获取数据,除了聚合。

有什么想法吗?

谢谢

4

1 回答 1

0

您不需要使用Join(请参阅Why use LINQ Join on a simple one-many relationship?),但您需要使用GroupBy.

var players = context.Players;
var activities = players.SelectMany(p => p.Activities);
var groups = activities.GroupBy(a => new 
{
    Name = a.Player.Name,
    Quarter = a.Quarter
});

var result = groups.Select(g => new 
{
    Name = g.Key.Name,
    Quarter = g.key.Quarter,
    Score = g.Sum(a => a.Score)
};
于 2012-08-26T11:06:33.543 回答