如何添加多个列并显示最大值?

时间:2019-04-22 19:18:43

标签: mysql

在以下代码中,我从排名表中添加了Fanbase,教练,TeamRanks,组织和踢球者。它返回每一行的总和。但是,我不确定如何显示总计的最大值。我不需要整个添加清单。

Select
  ID, 
  (Fanbase + Coach + TeamRanks + Organization + Kicker) as total,
  Fanbase, 
  Coach, 
  TeamRanks,
  Organization,
  Kicker
from Ranks;

这将返回每一列的总计,但是我需要最大值。总价值。

Team     Fanbase    Coach    TeamRanks    Organization     Kicker


Chargers  80         60       29           18               10
Patriots  100       100       32           32               20
RAMS      80        90        30           25               23

2 个答案:

答案 0 :(得分:1)

执行此操作最快的方法(并且无需从原始查询中获取太多信息),可以使用ORDER BY DESCLIMIT

-- Assuming that ID=teamname
SELECT ID FROM
(SELECT
  ID, 
  (Fanbase + Coach + TeamRanks + Organization + Kicker) AS total
FROM Ranks ORDER BY total DESC LIMIT 1) r;

更新:我想到了一个查询,但是我担心它可能无法在某些MySQL版本中使用,但是现在我有时间尝试一下,并且在MySQL 5.5上似乎运行良好,5.6、5.7和8.0。此查询要短得多,并且无需使用子查询:

SELECT ID
FROM ranks 
ORDER BY  (Fanbase + Coach + TeamRanks + Organization + Kicker) DESC 
LIMIT 1;

我还要指出,如果其中一列包含所有团队的NULL值;例如,如果所有Kicker的值均为NULL,则此查询似乎不起作用。我已经检查了数学公式,如果(Fanbase + Coach + TeamRanks + Organization + Kicker)=(10+ 10+ 20+ 30+ NULL),它将返回NULL而不是70。您可以添加类似IFNULL(field,0)的函数。例如,

SELECT ID
FROM ranks 
ORDER BY (IFNULL(Fanbase,0)+IFNULL(Coach,0)+IFNULL(TeamRanks,0)+IFNULL(Organization,0)+IFNULL(Kicker,0)) DESC 
LIMIT 1;

但是,最好的方法当然是将字段设置为默认0NOT NULL。在这里,我只关心What if ... ?

答案 1 :(得分:0)

使用MAX()函数汇总列。例如:

Select
  MAX(Fanbase + Coach + TeamRanks + Organization + Kicker) as max_total
from Ranks;

编辑:要获取具有max_total值的团队的数据,您可以执行以下操作:

Select
  ID, 
  (Fanbase + Coach + TeamRanks + Organization + Kicker) as total,
  Fanbase, 
  Coach, 
  TeamRanks,
  Organization,
  Kicker
from Ranks
where Fanbase + Coach + TeamRanks + Organization + Kicker = (
  Select
    MAX(Fanbase + Coach + TeamRanks + Organization + Kicker) as max_total
  from Ranks
)

如果有多个队伍,此查询将返回所有处于第一位置的队伍。