使用group by子句获取第二大日期

时间:2017-01-23 20:57:49

标签: mysql sql

我的表结构是这样的

catName    class   age
-------------------
AAA        4       19
AAA        3       14
AAA        3       12
AAA        3       9
BBB        7       12
BBB        6       12
BBB        7       17
CCC        8       10
DDD        9       10
DDD        9       11

我想要的结果是通过catName和class获得组的第二大年龄。 所以结果应该是

AAA 3 14
BBB 7 12
DDD 9 10

请帮我找到MySQL的查询

2 个答案:

答案 0 :(得分:2)

这有点棘手,但这里有一种方法:

select catname, class,
       (case when count(*) > 1
             then substring_index(substring_index(group_concat(age order by age desc), ',', 2), ',' -1)
             else max(age)
        end) as age
from t
group by catname, class;

答案 1 :(得分:0)

有点不清楚你实际上在追求什么 - 你的示例输出与你声明的要求不符。

如果存在,则下面的查询将返回每个组的第二高年龄。如果该组只有一个年龄,则不会返回任何年龄。

select  a.class,
        a.catName,
        max( age ) as second_highest_age
from    table1 as a
        left join
        (
            /* get the highest age for this class/catName */
            select  class,
                    catName,
                    max( age ) as maxAge
            from    table1
            group by class,
                    catName
        ) as b
        on a.class = b.class 
        and a.catName = b.catName
/* filter out records where the age is equal to the max age for this group */
/* this will leave the second-highest age in each group (if one exists) */
where   a.age <> b.maxAge
group by a.class,
        a.catName

SQLfiddle here