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

Deadly 提交于 2019-12-30 09:50:12

问题


My database structure is like

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 have to fetch the data using group by code and i want the middle row as output. In the above example i want the output as

Id     Price     Code
3      0.54      93
7      0.90      94

The above is the output that i want with the middle row or the row having maximum price value in case of two middle rows like in case of row count 4,6,8


回答1:


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




回答2:


It can be done by some tricks.

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

SQLFiddle



来源:https://stackoverflow.com/questions/14433948/my-sql-query-to-get-middle-row-values-using-group-by-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!