Sql 如何根据另一个属性';s值多少?
我有一个三栏的表格,分别是“年”、“学生人数”和“教员”。 我想知道每一个不同的教师的最大“学生数”是多少 该表如下所示:Sql 如何根据另一个属性';s值多少?,sql,sql-server,Sql,Sql Server,我有一个三栏的表格,分别是“年”、“学生人数”和“教员”。 我想知道每一个不同的教师的最大“学生数”是多少 该表如下所示: year| students_count| faculty ------------------------------------ 2001| 50 | Business 2002| 60 | Business 2003| 40 | Business 2001| 20 | Engine
year| students_count| faculty
------------------------------------
2001| 50 | Business
2002| 60 | Business
2003| 40 | Business
2001| 20 | Engineering
2002| 10 | Engineering
2003| 50 | Law
(不起作用)
如果您每年需要,需要分组,并且教员人数最多
SELECT year,max(students_count),faculty FROM table group by year,faculty
但是,如果您只需要功能,那么您可以使用相关子查询
select top (1) with ties t.*
from table_name t
order by row_number() over (partition by faculty order by students_count desc)
使用行编号()
您想要densite\u rank()
:
这将有助于:
select * from (select *,rank() over (partition by faculty order by sytudents_count desc
) rnk form tablename) where rnk=1;
为此,我认为您只需要在sql中使用GROUPBY。 这也许可以解决这个问题
Create Table School(
Year Number(4),
Students_Count Number(2),
Faculty Varchar2(20)
);
Insert Into School Values (2001,50,'Business');
Insert Into School Values (2002,60,'Business');
Insert Into School Values (2003,40,'Business');
Insert Into School Values (2001,20,'Engineering');
Insert Into School Values (2002,10,'Engineering');
Insert Into School Values (2003,50,'Law');
Select * From School;
Select Faculty,Max(Students_Count) From School
Group By Faculty;
您必须按每个组的字段进行分组以进行汇总。
select * from
(
select *,row_number() over(partition by faculty order by students_count desc) as rn
from tablename
)A where rn=1
select t.*
from (select t.*,
dense_Rank() over (partition by faculty order by students_count desc) as seq
from table t
) t
where seq = 1;
select * from (select *,rank() over (partition by faculty order by sytudents_count desc
) rnk form tablename) where rnk=1;
Create Table School(
Year Number(4),
Students_Count Number(2),
Faculty Varchar2(20)
);
Insert Into School Values (2001,50,'Business');
Insert Into School Values (2002,60,'Business');
Insert Into School Values (2003,40,'Business');
Insert Into School Values (2001,20,'Engineering');
Insert Into School Values (2002,10,'Engineering');
Insert Into School Values (2003,50,'Law');
Select * From School;
Select Faculty,Max(Students_Count) From School
Group By Faculty;