sql 練習

哎呀我的天吶發表於2015-08-25

要求:入職在2005年之前(老員工才有資格中獎 ),並且中獎員工是尾數為0的員工,我們要聯絡所在部門頒發獎品。

select d.department_id, d.department_name
  from departments d
 where exists (select 1
          from employees e
         where e.department_id = d.department_id
           and e.employee_id in
               (110, 120, 130, 140, 150, 160, 170, 180, 190, 200))
   and not exists
 (select 1
          from employees e
         where e.department_id = d.department_id
           and e.hire_date > to_date('2005-01-01', 'yyyy-mm-dd'))

執行計劃

丟東西了,日啊

(select d.department_id,
               d.department_name,
               max(case
                     when e.employee_id IN
                          (110, 120, 130, 140, 150, 160, 170, 180, 190, 200) then
                      1
                     else
                      null
                   end) as existscontion,
               max(case
                     when e.hire_date > to_date('2005-01-01', 'yyyy-mm-dd') then
                      1
                     else
                      null
                   end) as notexistscondition,
                   d.department_id
          from departments d
          left join employees e
            on d.department_id = e.department_id
         group by d.department_id, d.department_name ,d.department_id)

結果

select rs.department_id, rs.department_name
  from (select d.department_id,
               d.department_name,
               max(case
                     when e.employee_id IN
                          (110, 120, 130, 140, 150, 160, 170, 180, 190, 200) then
                      1
                     else
                      null
                   end) as existscontion,
               max(case
                     when e.hire_date > to_date('2005-01-01', 'yyyy-mm-dd') then
                      1
                     else
                      null
                   end) as notexistscondition
          from departments d
          left join employees e
            on d.department_id = e.department_id
         group by d.department_id, d.department_name) rs
 where existscontion is not null
   and notexistscondition is null


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29990276/viewspace-1782010/,如需轉載,請註明出處,否則將追究法律責任。

相關文章