Oracle SQL获取与max(count())关联的列值

时间:2012-03-05 05:06:04

标签: sql oracle

我有以下查询。结果是两个coloums,oakid和max(计数(评级))。我想要的是有两列,但实际上没有max(计数(评级)),我想要与max(计数(评级))相关的评级。如何修改我的查询给我这个?

select oakid, 
  (select max(count(rating)) 
     from climbs, routes 
     where climbs.routename = routes.name 
     and climbs.climberid = oakid group by routes.rating) 
  as skill
 from climbers;

例如,如果我有“硬,硬,容易,简单,容易,中等”的评级,则最大(计数(评级))将显示“3”,因为有3个“简单”评级,但我想要它显示“容易”,而不是“3”。

2 个答案:

答案 0 :(得分:2)

听起来好像您希望每个oakidclimberid都有statistical mode(最常出现的)评分。 Oracle为我们提供了一个方便的功能,称为STATS_MODE

SELECT c.climberid AS oakid, STATS_MODE(r.rating) AS skill
FROM climbs c
INNER JOIN routes r ON (c.routename = r.name)
GROUP BY c.climberid;

答案 1 :(得分:0)

尝试以下方法:

select oakid, 
  (select rating
     from climbs, routes 
     where climbs.routename = routes.name 
     and climbs.climberid = oakid 
         group by routes.rating 
         having max(count(rating)) = count(rating)) 
  as skill
 from climbers