【发布时间】:2012-05-05 20:54:43
【问题描述】:
我需要 (from_id, to_id) 的每个组合的结果,它具有最小值和匹配条件的循环。
所以基本上我需要具有最小值的循环。例如从 A 到 B 我需要最小值和 loop_id。
该表有以下字段:
value from_id to_id loop_id
-------------------------------------
2.3 A B 2
0.1 A C 2
2.1 A B 4
5.4 A C 4
所以结果将是:
value from_id to_id loop_id
-------------------------------------
2.1 A B 4
0.1 A C 2
我尝试了以下方法:
SELECT t.value, t.from_id, t.to_id,t.loop_id
FROM myresults t
INNER JOIN (
SELECT min(m.value), m.from_id, m.to_id, m.loop_id
FROM myresults m where m.loop_id % 2 = 0
GROUP BY m.from_id, m.to_id, m.loop_id
) x
ON (x.from_id = t.from_id and x.to_id=t.to_id and x.loop_id=t.loop_id )
AND x.from_id = t.from_id and x.to_id=t.to_id and x.loop_id=t.loop_id
但它正在返回所有循环。 提前致谢!
【问题讨论】:
-
从内部派生表中删除 loop_id,因此也将连接到外部查询。然后它将返回每个组合的最小值,并且在外部查询中您可以找到适当的 loop_id。
-
嗨,Kaj,你有那个查询的例子吗?谢谢
-
@baboso 这个查询怎么样。
SELECT min(value) as value, from_id, to_id from myresults group BY from_id,to_id -
@viswanathan-iyer 您的查询将返回所有循环。这也不起作用: SELECT min(value) as value, from_id, to_id, loop_id from myresults where loop_id % 2 = 0 group BY from_id,to_id,loop_id
-
@baboso 那么你想要哪个 loop_id?
标签: sql combinations