如果在pl sql

时间:2019-02-19 07:24:35

标签: sql oracle case

查询在TRUE条件下可以正确提取student_id,但在else条件下则不能提取(max(gr_number)+1)。以下是我的查询,请帮帮我。

 Select case when count(*) > 0 then student_id else (max(gr_number)+1) end student_id
 from student 
 where student_name ='faizan ahmed' 
 and email_id='abc@gmail.com' 
 and UPPER(student_dob)=UPPER('01-FEB-19') 
 and  rownum = 1 
 group by student_id, gr_number  ;

在else条件下返回null。

2 个答案:

答案 0 :(得分:2)

FALSE条件是count()不大于零时。因此,未找到任何记录时为FALSE。因此,NULL是正确的结果,因为gr_number为null(未找到记录),因此max(gr_number)为null,而max(gr_number)+1为null。

不确定要达到的目标,但这是一种解决方案,如果找不到特定的学生,该解决方案将返回一个值:

Select coalesce(s.student_id, g.gr_number+1) as student_id
from (select 1 as rn, max(gr_number) as gr_number
      from student ) g
left outer join
      ( select rownum as rn, student_id
        from student
        where student_name ='faizan ahmed' 
        and email_id='abc@gmail.com' 
        and UPPER(student_dob)=UPPER('01-FEB-19') 
        and  rownum = 1 ) s
 on s.rn = g.rn
  ;

答案 1 :(得分:0)

如果您尝试获取每个学生的最高gr_number,则不应仅按学生编号将其分组:

group by student_id;