查找每个中包含MAX值的记录

时间:2013-12-13 12:42:04

标签: mysql sql group-by max greatest-n-per-group

我正在使用mysql。这是一张桌子,例如:

  

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

在这张表中我有字段: CountryCityResourceVolumeother

我需要选择记录,其中每个Volume每个Resource City字段的 MAX 值<{1}} {{1} }}。 我试过这些查询:

Country

但数据搞砸了(在'其他'字段)。

要清楚这就是我想要实现的目标。

  

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

我需要WHOLE记录,其中包含 MAX SELECT `Country`, `City`, `Resource`, MAX(`Volume`), `other` FROM `temp` GROUP BY `Country`, `City`, `Resource` 值。

我已经阅读了SQL Select only rows with Max Value on a Column,并且知道有一个内部联接方式来解决这个问题 但是没有得到,如何通过多个分组来做到这一点。 谢谢你的阅读。

3 个答案:

答案 0 :(得分:4)

查看此更新后的小提琴: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

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

答案 1 :(得分:1)

由于您没有对other列进行分组,因此MySQL会从组中为您提供随机值。事实上,其他RDBMS(如SQL Server)甚至不允许您选择没有聚合函数或组的列。

因此,在您的情况下,解决方案取决于您要为other列返回的内容。您是否只想要属于具有最大音量的组的值?在这种情况下,做这样的事情:

SELECT `Country`, `City`, `Resource`, `Volume`, `other`
FROM `temp` t1
WHERE `Volume` = (SELECT MAX(`Volume`) FROM `temp` t2 WHERE t1.`Country` = t2.`Country`
                     AND t1.`City` = t2.`City` AND t1.`Resource` = t2.`Resource`)

答案 2 :(得分:0)

使用MySQL功能的集合中还有一种方法:User-Defined Variables

select Country, City, Resource, Volume,other 
from 
(
SELECT Country, City, Resource, Volume,other,
if(@c1<>Country OR @c2<>City OR @c3<>Resource,1,0) 
   as FlagField,
@c1:=Country,
@c2:=City,
@c3:=Resource
FROM temp, (Select @c1:='',@c2:='',@c3:='') as t1
ORDER BY Country, City, Resource,Volume DESC
) t2 
WHERE FlagField=1

SQLFiddle demo

此查询还解决了每个群组有多条记录Value=MAX(Value)时的问题。如果您使用JOIN子查询或WHERE Volume=(..MAX(Value)..)的方式,那么您还应该使用(例如)主查询中的另外一个Group BY来处理此问题,以便每个组只留一条记录。例如(@Aziz Shaikh查询):

SELECT temp.Country,temp.City,temp.Value,MAX(other)
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
GROUP BY temp.Country,temp.City,temp.Value
相关问题