如何在SQL中使用Sum和Group by建立两个表之间的关系

时间:2015-03-26 13:47:34

标签: mysql sql

我有2张桌子

1. players

id,GameID,playerName,playerGroup

2. scoretable

ID,playerID,playerScore

我正在尝试根据每个组中的playerScore的SUM搜索顶级玩家。 结果应该是: playername,playergroup,得分

一切都应该由玩家组

分组
SELECT players . * , SUM( st.playerScore ) AS playerScore, st.playerHole
FROM (SELECT * FROM players WHERE players.GameID = 7 GROUP BY players.playerName) players
LEFT JOIN scoretable st ON players.id = st.playerID
GROUP BY players.playerGroup
ORDER BY playerScore DESC

但结果是一个错误的playerName。 是否可以使用单个查询以其他方式执行此操作?

感谢

3 个答案:

答案 0 :(得分:1)

你的逻辑不正确。请试试这个: -

SELECT players.id, players.GameID, players.playerName, players.playerGroup, SUM( st.playerScore ) AS playerScore, st.playerHole
FROM players JOIN scoretable st ON players.id = st.playerID
WHERE players.GameID = 7
GROUP BY players.id, players.GameID, players.playerName, players.playerGroup
ORDER BY playerScore DESC

答案 1 :(得分:0)

这是LINQ版本,如果需要,可以转换为sql。

var topPlayers = m_context.players
    .Join(m_context.scoretable, player=> player.Id, scoretable=> scoretable.PlayerId, 
    (player, scoretable) => new { 
                                PlayerName = player.PlayerName, 
                                PlayerGroup = player.PlayerGroup, 
                                Score = scoretable.PlayerScore, 
                                GameId = player.GameId })
    .Where(w => w.GameId == 7)
    .GroupBy(g => new {g.PlayerGroup, g.PlayerName, g.PlayerScore})
    .Select(s => new {
        PlayerName = s.Key.PlayerName,
        PlayerGroup = s.Key.PlayerGroup,
        TotalScore = s.Sum(score => score.PlayerScore)
    })
    .OrderByDescending(o => o.TotalScore)
    .Take(10).ToList(); //10 is top 10

答案 2 :(得分:0)

SELECT p.id, p.GameID, p.playerName, p.playerGroup, SUM( st.playerScore ) AS playerScore, st.playerHole
FROM players p JOIN scoretable st ON players.id = st.playerID
WHERE players.GameID = 7
GROUP BY p.id, p.GameID, p.playerName, p.playerGroup
ORDER BY playerScore DESC
LIMIT 1