查找每个记录中具有 MAX 值的记录

Nik*_*sky 1 mysql sql group-by max greatest-n-per-group

我正在使用mysql。这是我制作的一张表格:

http://sqlfiddle.com/#!2/0ca23/1

在此表中,我有字段: Country, City, Resource, Volume,other

我需要选择包含每个每个字段的最大值的记录。我已经尝试过这些查询:VolumeResourceCityCountry

    SELECT `Country`, `City`, `Resource`, MAX(`Volume`), `other`
    FROM `temp`
    GROUP BY `Country`, `City`, `Resource`
Run Code Online (Sandbox Code Playgroud)

但数据被搞乱了(在“其他”字段)。

需要明确的是,这就是我想要实现的目标。

http://sqlfiddle.com/#!2/0ad62a/1

我需要完整的记录,其中包含最大值 Volume

我已经阅读过SQL Select only rows with Max Value on a Column并知道有一种 INNER JOIN - 解决该问题的方法,但不明白如何通过多个分组来做到这一点。感谢您的阅读。

Azi*_*ikh 5

检查您的更新的小提琴:http://sqlfiddle.com/#! 2/0ca23/4

SELECT temp.*
FROM temp
JOIN 
   (SELECT `Country`, `City`, `Resource`, MAX(`Volume`) AS MaxVol
   FROM `temp`
   GROUP BY `Country`, `City`, `Resource`) t
   ON temp.country = t.country 
   AND temp.city = t.city 
   AND temp.resource = t.resource 
   AND temp.volume = t.MaxVol
Run Code Online (Sandbox Code Playgroud)

该查询基本上是使用子查询对主表进行 INNER JOIN,该子查询获取每个国家、城市和资源的最大(卷)记录。子查询结果别名为 table t