选择max(value)和相应的行而不使用rownum或limit

时间:2017-10-05 07:07:36

标签: mysql oracle ansi

为教师提供加入日期的表格,需要写一个查询以查找大多数加入学校的老师,查询应显示当年加入的老师的年份和年份。
我已经使用Limit编写了查询得到结果,但是还有其他方法可以编写查询。

select
  count(teah_id) as no_of_teachers,
  substr(DATE_OF_JOINING,1,4) as year
from teacher
group by substr(DATE_OF_JOINING,1,4)
order by count(phy_id) desc
limit 1

1 个答案:

答案 0 :(得分:0)

您可以将当前查询放入CTE,然后重复使用以查找最高计数:

with cte as (
    select
        count(teah_id) as no_of_teachers,
        substr(DATE_OF_JOINING,1,4) as year
    from teacher
    group by substr(DATE_OF_JOINING, 1, 4)
)

select
    year,
    no_of_teachers
from cte
where
    no_of_teachers = (select max(no_of_teachers) from cte);