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
哪個[DBMS](https://en.wikipedia.org/wiki/DBMS)您使用的?什麼是**確切的**錯誤信息(** [編輯] **你的問題 - 做**不** **郵編或額外的信息在評論中) –
我想你需要使用COUNT代替SUM有部分查詢 –
您能否發佈您遇到的問題(錯誤信息)? – Susang