MySQL查询,max&球员的当前排名

时间:2017-12-29 20:44:49

标签: mysql

在我需要找到的玩家列表中找到最高评级和当前评级

Petr | 1 | 2016-12-01 00:00:00 
Petr | 2 | 2016-12-02 00:00:00 
Petr | 3 | 2016-12-03 00:00:00 
Oleg | 3 | 2016-12-01 00:00:00 
Oleg | 2 | 2016-12-02 00:00:00 
Oleg | 1 | 2016-12-03 00:00:00 

我想获得一个输出:

 name | min | current  
 Petr |  1  | 3 
 Oleg |  1  | 1 

为了找到最大值,我试试

SELECT t1.rank as min
FROM table t1
LEFT JOIN table t2
ON t1.name = t2.name AND t1.rank > t2.rank
WHERE t2.name IS NULL

等解决,找到当前的

SELECT t1.rank as current
FROM table t1
WHERE t1.dt=(SELECT MAX(dt) FROM table t2 WHERE t1.name = t2.name)

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找最低等级而不是最高等级。

要获得current,评分为最大日期,请使用GROUP BY,然后再次加入原始表格,以获取此最大日期的评分值:

SELECT
  t1.Name,
   MAX(t2.MinRating) AS MinRating,
  MAX(t1.Rating) AS Current
FROM yourTable AS t1
INNER JOIN
(
  SELECT Name, MIN(rating) AS MinRating, MAX(rateDate) AS MaxRateDate
  FROM yourTable
  GROUP BY Name
) AS t2 ON t1.Name = t2.Name AND t1.rateDate = t2.MaxRateDate
GROUP BY t1.Name;

fiddle demo

| Name | MinRating | Current |
|------|-----------|---------|
| Oleg |         1 |       1 |
| Petr |         1 |       3 |