2011-09-14 202 views
0

我想解決一個簡單的問題,但我越來越多的細節。選擇最大值

我有2個表,一個有員工,另一個有部門。我的問題:我試圖檢查哪個部門擁有最多的員工,並僅輸出特定的部門。

到目前爲止,我有:

select count(*) Number_of_employees 
     from department d, employee e 
     where d.department_id = e.department_id 
     group by department_name 

,輸出:

NUMBER_OF_EMPLOYEES  
---------------------- 
2      
4      
3      
3      
3 

我的目標是隻輸出與這與4名員工的部門僱員最多的部門。

我嘗試過使用MAX和JOIN,但是我不太擅長加入,所以我們將不勝感激。

回答

1
select department_name from 
     (select department_name, count(*) Number_of_employees 
      from department d, employee e 
      where d.department_id = e.department_id 
      group by department_name 
      order by 2 desc) 
    where rownum = 1 

應該做的。

HTH

+0

謝謝!如果沒有最終的rownum = 1,有沒有不同的方法可以解決這個問題? – Geo

3

@Zsolt Botykai

我認爲這是正確的,除了由需求爲了DESC,我不認爲你可以參考number_of_employees查詢裏面。 (反正你不能在oracle中)。

select department_name 
    from 
    (select department_name 
      ,number_of_employees 
     from 
     (select department_name, count(*) Number_of_employees 
      from department d, employee e 
      where d.department_id = e.department_id 
      group by department_name) 
     order by Number_of_employees DESC) 
    where rownum = 1 
+0

感謝您指出錯誤!我不在我的數據庫前面一段時間,只是在晚上撰寫答案:-) –

3

你可以做到這一點,這樣既避免了這個rownum:

select 
     max(d.department_name) keep (dense_rank first order by count(1) desc) as department_name 
     , count(1) as number_of_employees 
    from employee e 
    inner join department d on (e.department_id = d.department_id) 
    group by d.department_name 
    ; 
+0

感謝您的幫助 – Geo