我在一所大学里有一组不同的演讲厅,其ID(例如ABC1)和名称(例如The Theater A)。我想计算使用每个演讲厅的不同班级的数量,并根据班级数量 num (大多数班级, rank 1等)对演讲厅进行排名。是否清楚,还是需要澄清?
id | name | num | rank
-----------------------------
ABC1 | Theatre A | 42 | 1
ABC5 | Theatre E | 37 | 2
ABC7 | Theatre G | 25 | 3
ABC2 | Theatre B | 25 | 4
ABC3 | Theatre C | 10 | 5
ABC4 | Theatre D | 9 | 6
ABC6 | Theatre F | 0 | 7
到目前为止,我已经设法获得以下信息:
id | name
------------------
ABC1 | Theatre A
ABC2 | Theatre B
ABC3 | Theatre C
ABC4 | Theatre D
ABC5 | Theatre E
ABC6 | Theatre F
ABC7 | Theatre G
使用以下代码:
create or replace view Lecture_theatres
AS
SELECT distinct r.id, r.name
FROM Rooms r
JOIN Room_types t ON (r.rtype=t.id)
FULL JOIN Classes c ON (c.room = r.id)
WHERE
t.description='Lecture Theatre'
GROUP BY
r.id,r.name
;
我试图通过将 count(c.id)添加到以下内容来计算 num :
SELECT distinct r.id, r.name, count(c.id)
但是,这似乎返回特定班级使用任何会议室而不是特定演讲厅的次数。我不确定我是否提供足够的信息来解决此问题,但是如果缺少某些内容,请发表评论!
答案 0 :(得分:3)
这未经测试,我不确定window函数内部的汇总是否达到了我的预期。如果这不起作用,请删除RANK
函数,将语句用另一个SELECT
包围(因此将其用作子选择),然后再次将RANK
添加到外部选择列表中。如果两个房间的班级数量相同,此功能将为您提供相同的值。
SELECT r.id, r.name, COUNT(c.id) AS num, RANK() OVER (ORDER BY COUNT(c.id) DESC) AS rank
FROM rooms r
INNER JOIN room_types t ON t.id = r.rtype
LEFT JOIN classes c ON c.room = r.id
WHERE t.description='Lecture Theatre'
GROUP BY r.id --if this is a PK, this should be enough; otherwise add r.name as well
ORDER BY num DESC