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

Posted

技术标签:

【中文标题】如何显示多个项目,但每个项目仅显示年份和月份的最高值?【英文标题】:How to display multiple items but only the highest values in year and month for each? 【发布时间】:2021-08-30 09:26:09 【问题描述】:

我有以下两张表:

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;

但遗憾的是没有取得任何成功。

有好心人能告诉我怎么去吗? 谢谢!

【问题讨论】:

【参考方案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;

【讨论】:

MySQL 8.0 已经推出多年。如果您使用的是旧版本的 MySQL,您可以关注greatest-n-per-group 标签并查看过去的解决方案。

以上是关于如何显示多个项目,但每个项目仅显示年份和月份的最高值?的主要内容,如果未能解决你的问题,请参考以下文章

如何仅在月份、日期和年份中更改我的日期选择器显示

如何将 jQuery 日期选择器转换为仅选择月份和年份?

仅显示月份和年份的 Django DateField 日历?

EXTJS 5 - 仅日期选择器年份和月份

想要在 Windows 应用程序中将自定义的 Datetimepicker 显示为“仅月份和年份”(使用 C#)

如何仅在 Flutter 的 datepicker 中显示年份?