使用聚合函数max()oracle时出错

时间:2013-03-14 13:34:44

标签: oracle11g

我正在尝试运行查询

select * from OS_Historystep where step_name = '011' and finish_date = max(finish_date) ;

但是我收到错误

ORA-00934: group function is not allowed here
00934. 00000 -  "group function is not allowed here"
*Cause:    
*Action:
Error at Line: 12 Column: 72

我做错了什么?

由于

2 个答案:

答案 0 :(得分:3)

您不能在where子句中使用聚合。此外,您不能在单个选择中混合来自同一列的非聚合数据和聚合数据。您需要使用子查询:

select * 
from OS_Historystep hs1
where step_name = '011' 
and finish_date = (select max(finish_date) 
                   from OS_Historystep hs2 
                   where hs2.step_name = hs1.step_name);

答案 1 :(得分:2)

你不能像这样引用聚合。您要么必须像下面那样放置一个子查询(假设您希望max(finish_date)表示步骤011的最大完成日期而不是整个表中的最大完成日期(可能不返回任何行):< / p>

select * 
  from OS_Historystep 
 where step_name = '011' 
   and finish_date = (select max(finish_date) 
                        from OS_Historystep
                       where step_name = '011');

或使用分析函数

select *
  from (select s.*, rank() over (partition by step_name order by finish_date desc) rnk
          from OS_Historystep s
         where step_name = '011')
 where rnk = 1;