0

我有下表:

+----+-----------+-----+
| p1 | p2 | model| res |
+----+-----------+-----+
|  1 | a  | dog  |  1  |
|  2 | a  | dog  |  2  |
|  1 | b  | dog  |  3  |
|  2 | b  | dog  |  4  |
|  1 | a  | cat  |  10 |
|  2 | a  | cat  |  2  |
|  1 | b  | cat  |  10 |
|  2 | b  | cat  |  1  |
+----+-----------+-----+

我想要的是,对于 p1 和 p2 的每种组合,选择所有模型的 res 总和最低的那个)。在这种情况下,总分是:

p1=1, p2=a: 1+10=11
p1=2, p2=a: 2+2=4
p1=1, p2=b: 3+10=13
p1=2, p2=b: 4+1=5

所以我想得到下表:

+----+-----------+-----+
| p1 | p2 | model| res |
+----+-----------+-----+
|  2 | a  | dog  |  2  |
|  2 | a  | cat  |  2  |
+----+-----------+-----+

注意:可能有更多的 p 列(即 p3、p4、...)

为了获得上面所需的表,我应该使用什么 sql 选择查询?

4

2 回答 2

2

http://sqlfiddle.com/#!7/af26b/5

SELECT t1.*
FROM TEST t1
JOIN (
  SELECT p1, p2
  FROM TEST
  GROUP BY p1, p2
  ORDER BY SUM(res)
  LIMIT 1) t2 ON t1.p1 = t2.p1 AND t1.p2 = t2.p2
于 2013-08-11T14:38:40.810 回答
0

这样的事情会有帮助吗?

select * from the_table
group by model          # do it for each distinct model
order by res ascending  # to get the lower ones first so that limit can pick them
limit 1                 # for each group, i think it will do that.
于 2013-08-11T14:39:01.180 回答