You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从MySQL数据库提取各月份最接近当前日期的数据

MySQL提取各月份最接近当前日期的日期及对应颜色

假设你的数据表名为color_records,包含record_date(日期类型)和color(颜色字段)两个字段。可以通过以下SQL语句实现需求:

基础版(适用于数据均为历史日期,取每月最后一条记录)

SELECT cr.record_date, cr.color
FROM color_records cr
INNER JOIN (
    -- 按年月分组,获取每个月的最大日期
    SELECT DATE_FORMAT(record_date, '%Y-%m') AS month_group, MAX(record_date) AS latest_date
    FROM color_records
    GROUP BY month_group
) AS month_latest 
ON cr.record_date = month_latest.latest_date;

进阶版(适配当前月只取到当前日期之前的最近记录)

如果需要考虑当前日期所在月份,仅提取该日期之前最接近的记录,可以添加日期筛选条件:

SELECT cr.record_date, cr.color
FROM color_records cr
INNER JOIN (
    SELECT DATE_FORMAT(record_date, '%Y-%m') AS month_group, MAX(record_date) AS latest_date
    FROM color_records
    WHERE record_date <= CURDATE() -- 仅保留当前日期及之前的记录
    GROUP BY month_group
) AS month_latest 
ON cr.record_date = month_latest.latest_date;

语句说明

  1. 子查询通过DATE_FORMAT(record_date, '%Y-%m')将日期按「年月」分组,用MAX(record_date)获取每组内的最大日期(即该月最接近当前日期的记录)。
  2. 通过内关联原表,匹配最大日期对应的颜色字段,最终得到每个月的目标记录。

内容的提问来源于stack exchange,提问作者Michael Carrasco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:00:06