如何显示多个项目但每个项目仅显示年份和月份的最高值?

How to display multiple items but only the highest values in year and month for each?

我有以下两个表:

CREATE DATABASE IF NOT EXISTS springbootdb;
DROP TABLE IF EXISTS occupancy;
DROP TABLE IF EXISTS hotel;

CREATE TABLE hotel
(
    id      INT  NOT NULL PRIMARY KEY auto_increment,
    category int NOT NULL,
    name    TEXT NOT NULL,
    owner   TEXT NOT NULL,
    contact TEXT NOT NULL,
    address TEXT NOT NULL,
    city    TEXT NOT NULL,
    zip     TEXT NOT NULL,
    phone   TEXT NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE occupancy
(
    id              int not null primary key auto_increment,
    hotelid         int not null,
    month           int not null,
    year            int not null,
    room_utilization int not null,
    bed_utilization  int not null,
    room_count       int not null,
    bed_count        int not null,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

现在我想显示每个 hotel.id 和 hotel.name 以及 occupancy.room_count、occupancy.bed_count、occupancy.room_utilization 和 occupancy.bed_utilization - 但是只有每个 hotel.id 的最新条目,因此 occupancy.year 和 occupancy.month 中的每个条目都是最高值。

我尝试了一些东西,例如

SELECT springbootdb.hotel.id, springbootdb.hotel.name, springbootdb.occupancy.bed_count, springbootdb.occupancy.bed_utilization 
From springbootdb.hotel 
INNER JOIN springbootdb.occupancy 
ON hotel.id = occupancy.hotelid
order by springbootdb.occupancy.`year`, springbootdb.occupancy.`month` asc limit 1;

但不幸的是没有取得任何成功。

哪位好心人能告诉我怎么走吗? 谢谢!

这最好用 window functions 解决,但这需要您升级到 MySQL 8.0。

大致思路如下。

SELECT t.id, t.name, t.bed_count, t.bed_utilization
FROM (
  SELECT h.id, h.name, o.bed_count, o.bed_utilization, ROW_NUMBER() OVER (PARTITION BY h.id ORDER BY o.`year` DESC, o.`month` DESC) AS rownum
  FROM hotel AS h JOIN occupacy AS o ON h.id = o.hotelid
) AS t
WHERE t.rownum = 1;