我的SQL查询使用GROUP BY函数获取中间行值 [英] My sql query to get middle row values using GROUP BY function
本文介绍了我的SQL查询使用GROUP BY函数获取中间行值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据库结构就像
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
上面是我想要的输出,在中间两行的情况下,中间行或具有最大价格值的行,例如在行数4,6,8的情况下
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
推荐答案
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
这篇关于我的SQL查询使用GROUP BY函数获取中间行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文