如何在oracle中显示count()列记录的最大/最小值

时间:2014-12-07 01:17:24

标签: sql oracle11g

Oracle Query

select
  courses.name,
  count(gardener)
from
  attendances
  join courses using (course)
group by
  courses.name
order by
  count(gardener) asc

输出

╔═══════════╦═════════════════╗
║   NAME    ║ COUNT(GARDENER) ║
╠═══════════╬═════════════════╣
║ Harvesting║               3 ║
║ Planting  ║               3 ║
║ Gardening ║               4 ║
╚═══════════╩═════════════════╝

我如何才能显示最小/最大甚至平均数。例如。至少

// I just want to display the courses with minimum count
╔═══════════╦═════════════════╗
║   NAME    ║ COUNT(GARDENER) ║
╠═══════════╬═════════════════╣
║ Harvesting║               3 ║
║ Planting  ║               3 ║
╚═══════════╩═════════════════╝

我试过

select
 max(cnt), -- min(cnt) and avg(cnt) doesnt seem to work
 name
from
(
  select
    courses.name,
    count(gardener) as cnt
  from
    attendances
    join courses using (course)
  group by
    courses.name
  order by
    count(gardener) asc
)
group by
  name

我得到无效的标识符“cnt”。我尝试使用max(cnt)它也给了我相同的标识符错误,任何人都可以更正我的语法并建议我做错了或者建议采用不同的方法来做它?

编辑:我删除了语音标记,但仍然显示所有记录,而不仅仅是我需要的最大值count()记录。

2 个答案:

答案 0 :(得分:0)

删除双引号,然后重试

答案 1 :(得分:0)

如果你想要最低计数的课程,我会推荐分析功能:

select name, cnt
from (select c.name, count(gardener) as cnt,
             dense_rank() over (order by count(gardener)) as seqnum
      from attendances a join
           courses c
           using (course)
      group by c.name
     ) ca
where seqnum = 1;