分组最大值的同一行中的值

时间:2013-09-30 23:08:32

标签: mysql sql group-by

我有一张图片中颜色最常见的表格。它看起来像这样:

file | color  | count
---------------------
1    | ffefad | 166
1    | 443834 | 84
2    | 74758a | 3874
2    | abcdef | 228
2    | 876543 | 498
3    | 543432 | 3382
3    | abcdef | 483

我正在尝试为每张图片获取最常用的颜色。所以我希望我的结果是:

file | color  | count
---------------------
1    | ffefad | 166
2    | 74758a | 3874
3    | 543432 | 3382

所以我的问题似乎是我需要GROUP BY file列,而MAX()count列。但只是

SELECT h.file, h.color, MAX(h.count) FROM histogram GROUP BY h.file

不起作用,因为它不确定,因此颜色结果与计数结果中的行不匹配。

SELECT h.file, h.color, MAX(h.count) FROM histogram GROUP BY h.file, h.color

修复了确定性,但现在每一行都是“唯一的”,并返回所有行。

我无法找到一种方法来执行子查询或连接,因为我可以想到的唯一“正确”值,文件和计数,并不是它们本身的区别。

也许我需要一个更健全的架构?它是“我的”表,所以如果需要我可以改变它。

2 个答案:

答案 0 :(得分:1)

SELECT tbl.file, tbl.color, tbl.count
FROM tbl
LEFT JOIN tbl as lesser
ON lesser.file = tbl.file
AND tbl.count < lesser.count
WHERE lesser.file IS NULL
order by tbl.file

答案 1 :(得分:1)

select file , max(count)
FROM histogram 
GROUP BY h.file

这将给出文件的最大值(计数)。将其转换为子查询和内连接,以便它充当过滤器。

select h.file, h.colour, h.count
from histogram inner join
(select file , max(count) as maxcount
FROM histogram 
GROUP BY h.file) a
on a.file = h.file and a.maxcount = h.count

如果有超过1种颜色且具有相同的最大数量,则会响应2行。