Select 在 mysql 中排名最高的多行

Select multiple rows with highest rank in mysql

我正在使用 MySQL。

从这两个表中,我需要 select 为每张病床分配的护士人数最多的所有房间。如果有平局,这可以只有一个房间或多个房间。

Table分配

+--------+----------+
|护士 |房间 |
+--------+----------+
|911923 | 1 |
|916923 | 1 |
|931923 | 1 |
|931926 | 1 |
|931927 | 4 |
|931928 | 4 |
+--------+----------+

Table房间

+--------+--------+
|编号 |尺码 |
+--------+--------+
| 1 | 2 |
| 4 | 1 |
+--------+----------+

我正在尝试 select 排名最高的行,但限制 1 仅限制一个值,在此示例中,两个房间的排名相同。如果多行具有相同的排名,我如何 select 所有具有最高排名的行?

SELECT ROOM.number,
    (SELECT COUNT(*) FROM ALLOCATION
     WHERE ALLOCATION.room = ROOM.number) / ROOM.size AS nurses_per_bed, 
     DENSE_RANK() OVER (ORDER BY nurses_per_bed DESC) AS SEQ

FROM ROOM
LIMIT 1

一步一步:

  1. 汇总每个房间的分配以获得房间的护士数量。
  2. 加入房间和护士计数(即分配汇总结果)。
  3. 按比率对结果行进行排名。
  4. 仅显示排名第一的行。

查询:

select room, nurses, ratio
from
(
  select
    r.room,
    a.nurses,
    a.nurses / r.size as ratio,
    dense_rank() over (order by a.nurses / r.size) as rnk
  from room r
  join
  (
    select number as room, count(*) as nurses
    from allocation
    group by number
  ) a on a.room = r.room
) ranked
where rnk = 1
order by room;