I want to get
id a b c
--------------------
1 1 100 90
6 2 50 100
…from:
id a b c
--------------------
1 1 100 90
2 1 300 50
3 1 200 20
4 2 200 30
5 2 300 70
6 2 50 100
It’s the row with the smallest b group by a.
How to do it with sql?
EDIT
I thought it can be achieved by
select * from table group by a having min(b);
which I found later it’s wrong.
But is it possible to do it with having statement?
I’m using MySQL
This works because there should be no matching row
t2with the sameaand a lesserb.update: This solution has the same issue with ties that other folks have identified. However, we can break ties:
Assuming for instance that in the case of a tie, the row with the lower
idshould be the row we choose.This doesn’t do the trick:
Because
HAVING MIN(b)only tests that the least value in the group is not false (which in MySQL means not zero). The condition in aHAVINGclause is for excluding groups from the result, not for choosing the row within the group to return.