mysql> select count(account) n,avg(dif) dist,account from (select T2.account,abs(T1.value-T2.value) dif from rating T1,rating T2 where T1.account='Toba' and T2.account<>'Toba' and T1.apparel=T2.apparel and (abs(T1.value-T2.value) < 3)) T group by account order by N desc,dist asc; +---+--------+-----------+ | n | dist | account | +---+--------+-----------+ | 3 | 0.6667 | calenlass | | 2 | 0.0000 | David | | 2 | 0.5000 | Witoki | | 1 | 0.0000 | croy | | 1 | 0.0000 | kastein | | 1 | 0.0000 | Tigrael | +---+--------+-----------+ 6 rows in set (0.00 sec) mysql> select count(account) n,avg(dif) dist,account from (select T2.account,abs(T1.value-T2.value) dif from rating T1,rating T2 where T1.account='David' and T2.account<>'David' and T1.apparel=T2.apparel and (abs(T1.value-T2.value) < 3)) T group by account order by N desc,dist asc; +---+--------+-----------+ | n | dist | account | +---+--------+-----------+ | 2 | 0.0000 | Toba | | 1 | 0.0000 | calenlass | | 1 | 0.0000 | kastein | | 1 | 0.0000 | croy | | 1 | 0.0000 | Tigrael | | 1 | 0.0000 | Witoki | +---+--------+-----------+ 6 rows in set (0.01 sec)