2017-06-02 48 views
0
SELECT d.DEPARTMENT_NAME 
    FROM Department d, 
     Student s 
    WHERE d.DEPARTMENT_ID = s.DEPARTMENT_ID 
GROUP BY d.DEPARTMENT_NAME 
    HAVING COUNT(s.STUDENT_ID) < MAX(COUNT(s.STUDENT_ID)); 

該代碼用於加入學生和部門表。各部門之間的關鍵是department_id。需要找到沒有最多學生人數的部門。錯誤是組函數嵌套過深。不允許嵌套到3?使用加入和分組...有錯誤

這裏是確切的錯誤

ORA-00935:組函數嵌套太深

+4

哪個[DBMS](https://en.wikipedia.org/wiki/DBMS)您使用的?什麼是**確切的**錯誤信息(** [編輯] **你的問題 - 做**不** **郵編或額外的信息在評論中) –

+0

我想你需要使用COUNT代替SUM有部分查詢 –

+0

您能否發佈您遇到的問題(錯誤信息)? – Susang

回答

0

UPD。哦,史〜!我剛剛提到了與Oracle有關的問題。我不知道它的語法爲rank()函數,但我認爲它應該非常接近Sql Server。

這就是:

;with Department(DEPARTMENT_ID, DEPARTMENT_NAME) as (
    select 1, 'first' union all 
    select 2, 'second' union all 
    select 3, 'third' 
) 
, Student(STUDENT_ID, DEPARTMENT_ID) as (
    select 1, 1 union all 
    select 2, 2 union all 
    select 3, 2 union all 
    select 4, 2 union all 
    select 5, 3 union all 
    select 6, 3 union all 
    select 7, 3 
) 
, DepOrdered as (
    select 
     d.DEPARTMENT_ID, 
     d.DEPARTMENT_NAME, 
     s.StudentCnt, 
     -- rank departments by the number of students 
     rank() over (order by s.StudentCnt desc) as Rnk 
    from Department d 
    cross apply (
     -- for every department count its students 
     select 
      count(s.STUDENT_ID) StudentCnt 
     from Student s 
     where 
      d.DEPARTMENT_ID = s.DEPARTMENT_ID 
    ) s 
) 
select 
    DEPARTMENT_ID, 
    DEPARTMENT_NAME, 
    StudentCnt 
from DepOrdered 
where 
    -- Rnk = 1 would have all departments with max number of students 
    Rnk > 1