質問の指定が少し不十分です。
列の値に応じて、昇順または降順で結果を並べ替えます。
列は多くの値を取ります (複数の行があるため)。
ここで、order by
句は式を使用し、その上で行を並べ替えます。その表現はモルフォトロピックでなければなりません(;))
したがって、標準オラクルの従業員スキーマを想定すると、マネージャーは次のようになります。
select *
from emp e
where exists (select emp_id from emp where e.id=emp.mgr_id)
回避策のクエリは次のとおりです。
Select e.id, e.name, e.birth_date,
case
when (select count(*)
from emp e
where exists (select emp_id from emp where e.id=emp.mgr_id)
) --existence of manager
> 0 then birth_date - to_date('1-Jan-1000','dd-mon-yyyy')
else to_date('1-Jan-1000','dd-mon-yyyy') - birth_date
end as tricky_expression
from emp A
order by 4;
その表現はcase
; 定数 (マネージャーが存在することを決定するサブクエリ) を使用して、値を正から負に変更します。つまり、順序の方向を変更します。
更新:コメントの詳細:
select id, name, birth_date emp_type
from (
Select id, name, birth_date, emp_type,
case when cnt_mgr > 0 then birth_date - to_date('1-Jan-1000','dd-mon-yyyy')
else to_date('1-Jan-1000','dd-mon-yyyy') - birth_date
end as tricky_expression
from(
Select e.id, e.name, e.birth_date, emp_type,
count(case when emp_type='M' then 1 else 0 end) over() as mgr_count
from emp A
where your_conditions
)
order by tricky_expression
)
where rownum=1;