如何在sql中编写此查询

时间:2010-12-17 15:33:22

标签: sql mysql

如何在sql中编写此查询: 对于每场玩过两场以上比赛的玩家,请列出玩家姓名,奖金总额和每位玩家的游戏次数。结果应按降序排列。

我在播放器表中有这些属性: playerId,playerName,年龄 并在游戏表中这些attrubites: gameId,playerId,结果注意结果attrubie由(第一或第二或第三或......,或没有显示)填充,获胜者是结果=第一个

这是我的弱查询我没有得到正确的答案,但这就是我所能做的一切。任何想法

select playerName,count(*),count(*)
 from games,player
 where games.playerId=player.playerId
 group by games.results

5 个答案:

答案 0 :(得分:3)

您希望结合COUNT查看GROUP BYHAVING。这样的事情可能会(未经测试):

SELECT
   p.playerName
   ,COUNT(g.*)
   ,SUM(g.Winnings)  -- you didn't name this column
FROM
   games g
   INNER JOIN ON g.playerId = p.playerId
WHERE
   g.results = 1     -- whatever indicates this player was the winner
GROUP BY
   p.playerName
HAVING
   COUNT(g.*) > 2

答案 1 :(得分:0)

很难从你的问题中准确地收集到你需要的东西,但尝试这样的事情:

select playerName, count(*)
 from games g
 join player p ON g.playerId = p.playerId
 group by playerName
 having count(*) > 2
 order by games.results DESC

答案 2 :(得分:0)

*试试这个(就像你用英语说的那样......) (如果“奖金”是游戏中赢得的金额),那么:

  Select playerName, count(*) Games,  -- Number of game records per player
      Sum(g.Winnings) Winnings        -- Sum of a Winnings attribute (dollars ??)
  from player p Join Games g          -- from the two tables
    On g.PlayerId = p.PlayerId        -- connected using PlayerId
  Group by p.playerName               -- Output in one row per Player
  Having Count(*) > 2                 -- only show players w/more than 2 games
  Order By Sum(g.Winnings)            -- sort the rows based on Player Winnings

如果通过“奖金”表示赢得的比赛数量,那么......

  Select playerName, Count(*) Games, -- Number of game records per player
      Sum(Case g.WonTheGame          -- or whatever attribute is used
          When 'Y' Then 1            -- to specify that player won
          Else 0 End) Wins           -- Output in one row per Player
  From player p Join Games g         -- from the two tables
    On g.PlayerId = p.PlayerId       -- connected using PlayerId
  Group by p.playerName              -- Output in one row per Player
  Having Count(*) > 2                -- only show players w/more than 2 games
  Order By Sum(Case g.WonTheGame     -- Sort by Number of games Won
          When 'Y' Then 1 
          Else 0 End)

答案 3 :(得分:0)

试试这个:

SELECT playerName, COUNT(g.PlayerID) as NumberOfPlays
 FROM games g ,player p 
 WHERE g.playerId=p.playerId 
 GROUP BY g.PlayerID
 HAVING COUNT(g.PlayerID) > 1
 ORDER BY g.results DESC

SELECT - 要显示的数据
从 - 表格 在哪里 - 两个ID彼此匹配
GROUP BY - 游戏玩家ID,所以所有的计数都是正确的 HAVING - 确保他们玩过一场比赛 ORDER BY - 按照您希望的方式订购结果。

答案 4 :(得分:0)

select
playerName,
sum(if(games.result = 'first',1,0)) as wins,
count(*) as gamesPlayed
from player
join games on games.playerId = player.playerId
group by games.results
having count(*) > 2
order by count(*) desc;