SELECT house, AVG(salary) AS median FROM ( SELECT h.id as house, x.salary FROM person x, person y, house h WHERE x.houseid=h.id AND y.houseid=h.id GROUP BY x.salary, h.id HAVING ( ( SUM(SIGN(1-SIGN(y.salary-x.salary))))>=floor((COUNT(*)+1)/2 ) ) AND ( ( SUM(SIGN(1+SIGN(y.salary-x.salary))))>=floor((COUNT(*)+1)/2 ) ) ORDER BY h.id ) AS tmp GROUP BY house ;