开发者

MySQL SELECT value before MAX

How to select 1st, 2nd or 3rd value before MAX ?

usually we do it with order by and limit

SELECT * FROM table1
ORDER BY field1 DESC
LIMIT 2,1

but with my current query I don't know how to make it...

Sample table

+----+------+------+-------+
| id | name | type | count |
+----+------+------+-------+
|  1 | a    |    1 |     2 |
|  2 | ab   |    1 |     3 |
|  3 | abc  |    1 |     1 |
|  4 | b    |    2 |    开发者_如何学Python 7 |
|  5 | ba   |    2 |     1 |
|  6 | cab  |    3 |     9 |
+----+------+------+-------+

I'm taking name for each type with max count with this query

SELECT 
    `table1b`.`name`
FROM
    (SELECT 
        `table1a`.`type`, MAX(`table1a`.`count`) AS `Count`
    FROM
        `table1` AS `table1a`
    GROUP BY `table1a`.`type`) AS `table1a`
        INNER JOIN
    `table1` AS `table1b` ON (`table1b`.`type` = `table1a`.`type` AND `table1b`.`count` = `table1a`.`Count`)

and I want one more column additional to name with value before max(count)

so result should be

+------+------------+
| name | before_max |
+------+------------+
| ab   |          2 | 
| b    |          1 |
| cab  |       NULL | 
+------+------------+

Please ask if something isn't clear ;)


AS per your given table(test) structure, the query has to be as follows :

select max_name.name,before_max.count
from 
(SELECT type,max(count) as max
FROM `test` 
group by type) as type_max
join
(select type,name,count
from test 
) as max_name on (type_max.type = max_name.type and count = type_max.max )

left join
(select type,count
from test as t1
where count != (select max(count) from test as t2 where t1.type = t2.type)
group by type
order by count desc) as before_max on(type_max.type = before_max .type)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜