0

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?

5
  • 1
    What database engine do you use? And what have you already tried? Aug 11, 2013 at 14:31
  • I use sqlite. I have tried group by, but it doesn't do what I want. My question is: "What sql select query should I use in order to get the desired resulting table?"
    – Ofer
    Aug 11, 2013 at 14:35
  • Show us what you have tried, and explain how it didn't do what you wanted. It's not enough to say "I tried X, and it didn't work." Show us exactly what you tried, and then explain exactly how it didn't work. Otherwise, you're just asking us to write your code for you. Aug 11, 2013 at 14:48
  • I tried "select * from TEST group by p1", but I saw it's really not what I need, simply due to counting considerations (the number of rows I need are like DISTINCT model, and group by p1 and/or p2 would return something unrelated to that. Since I knew my approach was fundamentally flawed,I didn't want to waste anyone's time reading it.
    – Ofer
    Aug 11, 2013 at 15:02
  • Anyone have a better name for this question so that others can find it more easily?
    – Ofer
    Aug 12, 2013 at 7:15

2 Answers 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
1
  • That's really awesome, both your solution and that sqlfiddle link you gave. I didn't know about the LIMIT command. I'll read up on it now. Thanks!
    – Ofer
    Aug 11, 2013 at 15:05
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.