Reputation: 3143
I have the following table:
+----+-----------+-----+
| 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 |
+----+-----------+-----+
What I want, is for each combination of p1 and p2, select the one that gets the lowest sum for res over for all models). The sum scores in this case are:
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
So I would like to get the following table:
+----+-----------+-----+
| p1 | p2 | model| res |
+----+-----------+-----+
| 2 | a | dog | 2 |
| 2 | a | cat | 2 |
+----+-----------+-----+
Note: There may be more p columns (i.e p3, p4,...)
What sql select query should I use in order to get the desired table above?
Upvotes: 0
Views: 67
Reputation: 96454
Would something like this help?
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.
Upvotes: 0
Reputation: 125620
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
Upvotes: 2