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