帮助SELECT语句

时间:2010-01-03 22:20:58

标签: sql mysql

首先,我知道这是一个非常模糊的标题 - 我对SQL的了解非常薄弱,以至于我真的不知道我要问的具体细节,所以请耐心等待。

我有一个看起来像这样的表:

+--------+-----------+----------+--------+--------+
| gameid | team1     | team2    | score1 | score2 |
+--------+-----------+----------+--------+--------+
|      1 | New York  | Boston   |      1 |      2 |
|      2 | New York  | Boston   |      2 |      0 |
|      3 | Baltimore | New York |      3 |      1 |
|      4 | Boston    | New York |      3 |      0 |
+--------+-----------+----------+--------+--------+

如果gameid是唯一标识符,则score1对应于team1等的分数

我需要的是一个查询,它将产生一个特定团队对所有对手的胜负总和。例如,使用纽约,查询将创建下表:

+-----------+------+--------+
| team      | wins | losses |
+-----------+------+--------+
| Baltimore |    0 |      1 |
| Boston    |    1 |      2 |
+-----------+------+--------+

4 个答案:

答案 0 :(得分:2)

我现在无法访问SQL框(所以这可能是语法弱点)而且我不是db结构的忠实粉丝,但这应该让你顺利:

SELECT team, SUM(win) AS wins, SUM(loss) AS losses
FROM
 (SELECT team1 AS team, 
   CASE WHEN score1>score2 THEN 1 END AS win, 
   CASE WHEN score2>score1 THEN 1 END AS loss
  FROM YourTable
  UNION ALL
  SELECT team2 AS team, 
   CASE WHEN score2>score1 THEN 1 END AS win, 
   CASE WHEN score1>score2 THEN 1 END AS loss
  FROM YourTable)
GROUP BY team

此外,这忽略了关系。

注意:我做了这个CW - 请更新,如果你可以改进它

答案 1 :(得分:1)

这是可能的,但查询会变得非常复杂。如果可能,也许您可​​以重新组织模式以将更多信息编码到其中。例如,您可以team1team2而不是winning_teamlosing_team;同样地,使用winning_scorelosing_score,您无需检查哪个分数与哪个团队相对应。然后你可以在GROUP BYlosing_team获得特定团队与其他团队的所有胜利,并在winning_team上获得一个以获得损失(并且完全避免使用得分)这个特殊的查询)。

答案 2 :(得分:1)

同样来自@ David的评论,如果您的表结构更加规范化,这将会更容易,但是,使用模式,尝试此SQL

  Select T.Team,
     Sum(Case When S1.Score1 > S1.Score2 Or 
                   S2.Score2 > S2.Score1 Then 1 Else 0 End) Wins,
     Sum(Case When S1.Score1 < S1.Score2 Or 
                   S2.Score2 < S2.Score1 Then 1 Else 0 End Losses,
     Sum(Case When S1.Score1 = S1.Score2 Or 
                   S2.Score2 = S2.Score1 Then 1 Else 0 End Ties     
   (Select Distinct team1 team from Table
    Union Select Distinct team2 team from Table) T
      Left Join Table S1
         On S1.Team1 = T.Team
      Left Join Table S2
         On S2.Team2 = T.Team
  Group By T.Team

答案 3 :(得分:0)

试试这个..

SELECT 
     team
    ,sum(wins) as wins
    ,sum(losses) as losses
FROM
    (
    SELECT 
         team1 as team
        ,SUM(CASE WHEN score1 > score2 THEN 1 ELSE 0 END) as wins
        ,SUM(CASE WHEN score1 < score2 THEN 1 ELSE 0 END) as losses
    FROM
        myTable
    GROUP BY
        team1
    UNION ALL
    SELECT 
         team2 as team
        ,SUM(CASE WHEN score2 > score1 THEN 1 ELSE 0 END) as wins
        ,SUM(CASE WHEN score2 < score1 THEN 1 ELSE 0 END) as losses
    FROM
        myTable
    GROUP BY
        team2 
    ) a
GROUP BY
team