MySQL sum()并加入一个查询

时间:2013-04-23 07:09:55

标签: mysql

我有两个表:一个Standings表和一个Teams表。

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 |名字| leagueid

1 | alphas | 1

2 |贝塔斯| 1

3 | gammas | 1

常设

id | teamid | weekid | seasonid |点

(阿尔法)

1 | 1 | 1 | 1 | 1

2 | 1 | 2 | 1 | 4

3 | 1 | 3 | 1 | 3

(BETAS)

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

我希望返回的表格如下:

姓名|点

Alphas | 8

Betas | 9

Gammas | 13

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

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

 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;