我该怎么做这个sql select查询?

时间:2013-08-11 14:28:36

标签: sql sqlite

我有下表:

+----+-----------+-----+
| 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的每个组合,选择获得所有模型的最低总和的那个。 在这种情况下的总分是:

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 select查询来获取上面所需的表?

2 个答案:

答案 0 :(得分: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 :(得分: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.