选择SUM()查询的MAX()

时间:2013-12-03 00:20:37

标签: mysql mysql-workbench

我正在尝试创建一个查询,该查询显示最大值以及总和查询中的团队名称。我试过四处搜索,大部分答案都使用LIMIT和TOP 1,这不是我想要的。

所以从这个SUM查询:

SELECT Team_Name, SUM(SCORE) as Score_Total
FROM SCORE, TEAM
WHERE team.Team_ID = score.Team_ID
GROUP BY Team_Name;

返回:

+----------------+-------------+
|   Team_Name    | Score_Total |
+----------------+-------------+
| Hackers        |         332 |
| Hammer Time    |         356 |
| Sharp Shooters |         406 |
| String Music   |         355 |
+----------------+-------------+

当我尝试使用以下代码在sum查询中使用MAX函数时:

SELECT Team_Name, MAX(Score_Total)
FROM (
SELECT Team_Name, SUM(SCORE) as Score_Total
FROM SCORE, TEAM
WHERE team.Team_ID = score.Team_ID
GROUP BY Team_Name) s;

我明白了:

+-----------+------------------+
| Team_Name | MAX(Score_Total) |
+-----------+------------------+
| Hackers   |              406 |
+-----------+------------------+

正如您所看到的,最大值确实是正确的,但与最大值对应的团队名称不是。我的代码有问题吗?

3 个答案:

答案 0 :(得分:2)

考虑这个问题:

SELECT Team_Name, MAX(Score_Total), MIN(Score_Total)
FROM (
SELECT Team_Name, SUM(SCORE) as Score_Total
FROM SCORE, TEAM
WHERE team.Team_ID = score.Team_ID
GROUP BY Team_Name) s;

它应返回哪个团队名称?得分最高的球队或得分最低的球队?如果汇总AVG() none 的行包含值,该怎么办?

团队名称不是来自找到最大(或最小)值的行。事实上,MySQL允许查询不明确。它返回列中众多团队名称之一,但它返回的是任意团队。

请注意,“任意”并不意味着“随机”。实际上,MySQL返回它在组中找到的第一个值。但这不是保证行为的一部分,而且只是实施的巧合。如果他们在某个未来版本中更改了实现,并且它开始从组中返回不同选择的任意行,则不允许您进行投诉。 ; - )

这种类型的查询实际上是大多数SQL品牌和SQL标准中的错误。您可以根据SET SQL_MODE=ONLY_FULL_GROUP_BY的SQL标准使MySQL的行为更严格。

解决您问题的最简单方法是:

SELECT Team_Name, SUM(SCORE) as Score_Total
FROM SCORE, TEAM
WHERE team.Team_ID = score.Team_ID
GROUP BY Team_Name
ORDER BY Score_Total DESC
LIMIT 1;

答案 1 :(得分:1)

如果未在查询中指定分组条件,MySQL将返回任何随机值。

如果您想要子查询中的最大值,我建议您订购数据集,然后只获取第一行:

select team_name, score_total
from
    (
        select team_name, sum(score) as score_total
        from score, team
        where team.team_id = score.team_id
        group by team_name
    ) as a
order by
    score_total desc
limit 1;

一点建议:

where子句进行笛卡尔连接和过滤的插入,使用连接。此外,按Id字段分组:

select team_name, score_total
from
    (
        select team_name, sum(score) as score_total
        from 
            score as s 
            inner join team as t on s.team_id = t.team_id
        group by 
            t.team_id
    ) as a
order by
    score_total desc
limit 1;

更简单的方法:

select team_name, sum(score) as score_total
from score as s inner join team as t on s.team_id = s.team_id
group by team_id
order by sum(score) desc
limit 1

答案 2 :(得分:0)

好的,所以根据你的表结构,你可以这样做

SELECT t1.Team_Name, SUM(s1.score) as score FROM SCORE s1
INNER JOIN TEAM t1 USING (Team_ID)
GROUP BY s1.Team_ID
UNION
SELECT t2.Team_Name, MAX(s2.score) as maxscore FROM SCORE s2
INNER JOIN TEAM t2 USING (Team_ID)
GROUP BY s2.Team_ID
UNION
SELECT t3.Team_Name, MIN(s3.score) as minscore FROM SCORE s3
INNER JOIN TEAM t3 USING (Team_ID)
GROUP BY s3.Team_ID