My sql query to get middle row values โ€‹โ€‹using GROUP BY function

My database structure is similar to

Id Price Code 1 0.12 93 2 0.13 93 3 0.54 93 4 0.96 93 5 0.10 94 6 0.30 94 7 0.90 94 8 1.40 94 9 2.30 94 

I need to get data using a group by code, and I want the middle row to be output. In the above example, I want the result to be like

 Id Price Code 3 0.54 93 7 0.90 94 

The above result I want with a middle row or row having a maximum price value in the case of two middle rows, for example, in the case of the number of rows 4,6,8

+4
source share
2 answers
 SELECT table1.* FROM table1 JOIN ( SELECT SUBSTRING_INDEX(SUBSTRING_INDEX( GROUP_CONCAT(id ORDER BY id ASC), ',', CEIL(COUNT(*) / 2) ), ',', -1) AS id FROM table1 GROUP BY CODE ) t USING(id) 

http://sqlfiddle.com/#!2/fdc22/14

+1
source

This can be done with some tricks.

 SELECT id, price, code FROM table1 WHERE id IN (SELECT Ceil(Avg(id)) AS `id` FROM table1 GROUP BY code); 

SQLFiddle

+2
source

All Articles