A sub query should work fine in this case. You can try something like below:
Select v1, v2, v3 from test a
where (select min(v2)
from test b
where a.v1 = b.v1) = v2;
题
I create a test data set using the following commands in MySQL:
CREATE TABLE test
(v1 INT,
v2 INT,
v3 INT);
INSERT INTO test (v1,v2,v3) VALUES(1,3,300);
INSERT INTO test (v1,v2,v3) VALUES(1,2,200);
INSERT INTO test (v1,v2,v3) VALUES(1,1,100);
INSERT INTO test (v1,v2,v3) VALUES(2,9,900);
INSERT INTO test (v1,v2,v3) VALUES(2,7,700);
INSERT INTO test (v1,v2,v3) VALUES(2,5,500);
I want to find the minimum of v2 while grouping by v1 and to display the value for v3 matching the minimum of v2. In other words:
v1 v2 v3
1 1 100
2 5 500
When I run the following:
SELECT v1,MIN(v2),v3 FROM test
GROUP BY v1;
I get:
v1 v2 v3
1 1 300
2 5 900
How do I get the desired output?
解决方案
A sub query should work fine in this case. You can try something like below:
Select v1, v2, v3 from test a
where (select min(v2)
from test b
where a.v1 = b.v1) = v2;