有一张表,包含教师,年份和课程。 我必须找到老师教授的每年(2005年至2010年)每组课程的前三名
我按照课程,年份,老师对课程进行分组并计算课程 例如,如果我有
,则为lesson1lesson1 year1 teachera 20
lesson1 year1 teacherb 1
lesson1 year1 teacherd 10
lesson1 year1 teachere 5
lesson1 year1 teacherf 0
lesson1 year3 teacherc 1
lesson1 year4 teacherb 8
我必须在第一年获得20分,10分和5分 第3年为1,第4年为8
我有大约40节课
答案 0 :(得分:1)
如果你正在使用Oracle(当你标记你的问题时),这将有效:
SELECT *
FROM
(
select Lesson, Year, Name, Count,
ROW_NUMBER() OVER (PARTITION BY Lesson, Year, Name ORDER BY Count DESC) as RN
from A
)t
WHERE RN <= 3;
它在MySQL中不起作用(因为你在sqlfiddle中创建它),但我相信你有理由在那里做同样的事情。
答案 1 :(得分:0)
这就是我的工作方式,谢谢
SELECT Lesson, Year, Name, Count
FROM
(
SELECT Lesson, Year, Name, Count,
RANK() OVER (PARTITION BY Lesson, Year, Name ORDER BY Count DESC)
as RK
from A
) t
WHERE RK <= 3;
答案 2 :(得分:-1)
您应该使用分析功能来实现它
如下所示
SELECT Lesson, Year, Name, Count
FROM
(
select Lesson, Year, Name, Count,
DENSE_RANK() OVER (PARTITION BY Lesson, Year, Name ORDER BY Count DESC) as RK
from A
)t
WHERE RK <= 3;