jaraisyn jaraisyn - 1 month ago 18
SQL Question

Nested case in select

Where is my mistake?

select dr.ders_code, dr.year,
case when dr.muf_sq is not null then
case when (select muf_sq_id from mufredat_sq m join ders_stud_ref dr on dr.muf_sq = m.muf_sq_id) = dr.muf_sq then dr.muf_sq end
end
from ders_stud_ref dr

Answer

The first mistake is

select muf_sq_id 
                from mufredat_sq m  
                join ders_stud_ref dr on dr.muf_sq = m.muf_sq_id

may return more then one row

I think you need something like

select dr.ders_code, dr.year, 
case when dr.muf_sq is not null then 
case when exists (select muf_sq_id 
            from mufredat_sq m  
           where dr.muf_sq = m.muf_sq_id) then dr.muf_sq end
end 
from ders_stud_ref dr