0

我有两个表:一个排名表和一个团队表。

Standings has 5 columns: id, teamid, weekid, seasonid, points
Teams has 3 columns: id, name, leagueid

我想获得该团队参与的所有周的所有积分的总和,并以该团队的 ID 加入该团队。

我不知道如何在单个查询中执行此操作,但是

SELECT sum(s.points), t.name FROM Standings s INNER JOIN Teams t ON s.teamid = t.id WHERE t.leagueid = 1 AND s.seasonid = 1 ORDER BY sum(s.points) DESC LIMIT 3

是我想要的。谢谢。

编辑:

我遇到的一个大问题是我实际上不允许为此访问架构,但我在具有这些类型值的测试数据集上使用它:

团队

编号 | 姓名 | 联盟ID

1 | 阿尔法 | 1

2 | 测试版 | 1

3 | 伽玛 | 1

常设

编号 | 团队ID | 周末 | 季节| 积分

(阿尔法)

1 | 1 | 1 | 1 | 1

2 | 1 | 2 | 1 | 4

3 | 1 | 3 | 1 | 3

(测试版)

4 | 2 | 1 | 1 | 7

5 | 2 | 2 | 1 | 0

6 | 2 | 3 | 1 | 2

(伽马)

7 | 3 | 1 | 1 | 4

8 | 3 | 2 | 1 | 4

9 | 3 | 3 | 1 | 5

我希望返回的表格看起来像:

姓名 | 积分

阿尔法 | 8

测试版 | 9

伽玛 | 13

4

3 回答 3

0

尝试将用于选择的列放在

SELECT
  Teams.name,
  SUM(Standings.points) AS StandingPoints,
  Standings.seasonid,
  Teams.leagueid
FROM Teams
  INNER JOIN Standings
    ON Teams.id = Standings.teamid
GROUP BY Teams.id
HAVING Teams.leagueid = 0
    AND Standings.seasonid = 0
ORDER BY StandingPoints DESC
LIMIT 3
于 2013-04-23T07:40:04.287 回答
0
SELECT
  Teams.name,
  SUM(Standings.points) AS StandingPoints
FROM Teams
  INNER JOIN Standings
    ON Teams.id = Standings.teamid
WHERE Teams.leagueid = 0
    AND Standings.seasonid = 0
GROUP BY Teams.id
ORDER BY StandingPoints DESC
LIMIT 3
于 2013-04-23T07:49:28.423 回答
0

我想不出为什么其他人使用 HAVING 子句作为 WHERE 标准,所以我会发布我的版本(非常像你的原版):

 SELECT t.*
      , s.seasonid
      , SUM(s.points) total
   FROM Team t 
   JOIN Standing s
     ON s.teamid = t.id 
    AND s.seasonid = 1
  WHERE t.leagueid = 1
  GROUP 
     BY t.id
      , s.seasonid
  ORDER
     BY total DESC;
于 2013-04-23T07:52:53.407 回答