| SELECT t1.cat_id, round( avg (t1.price), 1) price FROM ( SELECT * FROM ( SELECT t.cat_id, t.price, count (*) AS rank FROM test t LEFT OUTER JOIN test r ON t.cat_id = r.cat_id AND t.price <= r.price GROUP BY t.cat_id, t.price ORDER BY t.cat_id, t.price DESC ) s ) t1, ( SELECT DISTINCT a.cat_id, round(a.maxrank / 2) rank FROM ( SELECT cat_id, max (rank) maxrank, MOD ( max (rank), 2) modrank FROM ( SELECT * FROM ( SELECT t.cat_id, t.price, count (*) AS rank FROM test t LEFT OUTER JOIN test r ON t.cat_id = r.cat_id AND t.price <= r.price GROUP BY t.cat_id, t.price ORDER BY t.cat_id, t.price DESC ) s ) t1 GROUP BY cat_id ) a, ( SELECT * FROM ( SELECT t.cat_id, t.price, count (*) AS rank FROM test t LEFT OUTER JOIN test r ON t.cat_id = r.cat_id AND t.price <= r.price GROUP BY t.cat_id, t.price ORDER BY t.cat_id, t.price DESC ) s ) b WHERE a.cat_id = b.cat_id AND a.modrank = 0 UNION ALL SELECT DISTINCT a.cat_id, round(a.maxrank / 2) + 1 rank FROM ( SELECT cat_id, max (rank) maxrank, MOD ( max (rank), 2) modrank FROM ( SELECT * FROM ( SELECT t.cat_id, t.price, count (*) AS rank FROM test t LEFT OUTER JOIN test r ON t.cat_id = r.cat_id AND t.price <= r.price GROUP BY t.cat_id, t.price ORDER BY t.cat_id, t.price DESC ) s ) t1 GROUP BY cat_id ) a, ( SELECT * FROM ( SELECT t.cat_id, t.price, count (*) AS rank FROM test t LEFT OUTER JOIN test r ON t.cat_id = r.cat_id AND t.price <= r.price GROUP BY t.cat_id, t.price ORDER BY t.cat_id, t.price DESC ) s ) b WHERE a.cat_id = b.cat_id AND a.modrank = 0 UNION ALL SELECT DISTINCT a.cat_id, round(a.maxrank / 2) rank FROM ( SELECT cat_id, max (rank) maxrank, MOD ( max (rank), 2) modrank FROM ( SELECT * FROM ( SELECT t.cat_id, t.price, count (*) AS rank FROM test t LEFT OUTER JOIN test r ON t.cat_id = r.cat_id AND t.price <= r.price GROUP BY t.cat_id, t.price ORDER BY t.cat_id, t.price DESC ) s ) t1 GROUP BY cat_id ) a, ( SELECT * FROM ( SELECT t.cat_id, t.price, count (*) AS rank FROM test t LEFT OUTER JOIN test r ON t.cat_id = r.cat_id AND t.price <= r.price GROUP BY t.cat_id, t.price ORDER BY t.cat_id, t.price DESC ) s ) b WHERE a.cat_id = b.cat_id AND a.modrank = 1 ) t2 WHERE t1.cat_id = t2.cat_id AND t1.rank = t2.rank GROUP BY t1.cat_id |