select q1.* from ( select m.mes_typos, m.mes_onoma, max(d.diaf_kostos) from diafimisi as d, meso as m where d.diaf_mes_kwdik = m.mes_kwdikos group by m.mes_typos,m.mes_onoma ) q1 join ( select m.mes_typos, max(d.diaf_kostos) from diafimisi as d, meso as m where d.diaf_mes_kwdik = m.mes_kwdikos group by m.mes_typos ) q2 using (mes_typos, max);