7

列の値に応じて昇順または降順で結果を並べ替えるクエリがあります。

例えば

マネージャー タイプの従業員が存在する場合 THEN join_date, bit_date ASC による順序 従業員が開発者の場合 THEN Join_date,birth_date DESC による順序。

以下のようなことを達成したいのですが、それを達成できません。

ORDER BY CASE WHEN employee_type = 'm'  
              THEN joining_date, birth_date ASC;
              WHEN employee_type = 'd' 
              THEN joining_date, birth_date  DESC; 
4

4 に答える 4

15

さて、私はいくつかの研究の後に答えを得ました。

次のように、条件付きで where 句に複数の列を追加できます。

ORDER BY DECODE(employee_type, 'm', joining_date, birth_date, salary) ASC,
         DECODE(employee_type, 'd', joining_date, birth_date, salary) DESC

これにより、employee_type に基づいて結果が並べ替えられます。

于 2013-01-31T07:55:21.823 に答える
5

次のようなものが必要だと思います:

ORDER BY 
    employee_type DESC             -- first all the managers, then the developers
                                   -- and in every one of these two groups
  , joining_date                   -- first order by joining date
  , CASE WHEN employee_type = 'm'  -- and then either by
        THEN birth_date            -- birth date ascending for managers
        ELSE NULL
    END                            -- or
  , birth_date DESC ;              -- birth date descending for the rest (devs)
于 2013-01-31T08:11:09.507 に答える
0

質問の指定が少し不十分です。

列の値に応じて、昇順または降順で結果を並べ替えます。

列は多くの値を取ります (複数の行があるため)。

ここで、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;
于 2013-01-30T06:42:29.303 に答える
0

会社にマネージャーがいる場合、このクエリは最年長のマネージャーを返し、そうでない場合は最年少の開発者を返します。

select 
  id, name, birth_date, emp_type
from emp
where 
  id = (select 
           max(id) keep (dense_rank first order by 
             decode(emp_type, 'M', 1, 'D', 2),
             joining_date,
             decode(emp_type, 'M', 1, 'D', -1) * (birth_date - to_date('3000','yyyy')))
        from emp)
于 2013-01-30T08:20:51.157 に答える