MySQL aggregate function to find closest value -
in mysql, there aggregate function (or other method) find closest value specific value?
for example, i'm looking addresses, house number 15. or, when streets doesn't have house no 15, closest house number (like 14 or 16) should returned:
select closest(house_no, 15), street_name addresses group street_name
since there's need aggregate, can't see order abs(house_no - 15) limit 1
used single result.
drop table if exists my_table; create table my_table (street varchar(12) not null ,house_no int not null ,primary key(street,house_no) ); insert my_table values ('street_1',11), ('street_1',12), ('street_1',13), ('street_1',14), ('street_2',12), ('street_2',13), ('street_2',14), ('street_2',15), ('street_3',13), ('street_3',14), ('street_3',16), ('street_4',16), ('street_4',17), ('street_4',18), ('street_4',19); select x.* my_table x join ( select street, min(abs(house_no-15)) best_match my_table group street) y on y.street = x.street , y.best_match = abs(x.house_no-15); +----------+----------+ | street | house_no | +----------+----------+ | street_1 | 14 | | street_2 | 15 | | street_3 | 14 | | street_3 | 16 | | street_4 | 16 | +----------+----------+
Comments
Post a Comment