php MySQL获取每个月的最后一个日期的记录

3lxsmp7m  于 2023-06-20  发布在  PHP
关注(0)|答案(2)|浏览(152)

我需要根据数据库表中记录的日期获取每个月last date的记录。现在,如果我使用以下查询获取表中每个月的最后日期:

SELECT MAX(`date`) AS max_date 
FROM cpr
WHERE YEAR(`date`) = YEAR(CURRENT_DATE())
GROUP BY YEAR(`date`), MONTH(`date`);

它完美地返回每个月的最后日期,如下所示:

max_date
2023-01-31
2023-02-27
2023-03-31
2023-04-27
2023-05-31
2023-06-06

现在,如果我使用相同的查询来获取该日期的剩余数据,它只返回2023-01-31的记录,即使在上面的查询中使用了ORDER BYdateDESC
下面是我正在尝试的查询:

SELECT * FROM cpr
INNER JOIN (
    SELECT MAX(`date`) AS max_date 
    FROM cpr
    WHERE YEAR(`date`) = YEAR(CURRENT_DATE())
    GROUP BY YEAR(`date`), MONTH(`date`)
)
AS monthwise ON cpr.`date` = monthwise.max_date

另一个:

SELECT * FROM cpr
WHERE `date` IN (
    SELECT MAX(`date`)
    FROM cpr
    WHERE YEAR(`date`) = YEAR(CURRENT_DATE())
    GROUP BY YEAR(`date`), MONTH(`date`)
)

任何帮助将不胜感激。TIA:)

bqucvtff

bqucvtff1#

使用窗口函数!这比子查询和自连接更简单,而且通常更有效:

select *
from (
    select c.*, 
        row_number() over(partition by year(date), month(date) order by date desc) rn
    from cpr c
) c
where rn = 1

注意:窗口函数在MySQL 8.0版本开始可用。

kmynzznz

kmynzznz2#

只需将SELECT语句中的*替换为cpr.*,如下所示:

SELECT cpr.*
FROM cpr
INNER JOIN ( 
    SELECT MAX(`date`) AS max_date 
    FROM cpr WHERE YEAR(`date`) = YEAR(CURRENT_DATE()) 
    GROUP BY YEAR(`date`), MONTH(`date`) 
) AS max_dates ON cpr.`date` = max_dates.max_date

相关问题