gpt4 book ai didi

mysql - 从 DATETIME 中选择每年每个月的最后插入值

转载 作者:搜寻专家 更新时间:2023-10-30 20:03:48 25 4
gpt4 key购买 nike

当引入值时,我得到了一个 DATETIME 来存储,如下例所示:

CREATE TABLE IF NOT EXISTS salary (
change_id INT(11) NOT NULL AUTO_INCREMENT,
emp_salary FLOAT(8,2),
change_date DATETIME,
PRIMARY KEY (change_id)
);

我将这样填写示例:

+-----------+------------+---------------------+
| change_id | emp_salary | change_date |
+-----------+------------+---------------------+
| 1 | 200.00 | 2018-06-18 13:17:17 |
| 2 | 700.00 | 2018-06-25 15:20:30 |
| 3 | 300.00 | 2018-07-02 12:17:17 |
+-----------+------------+---------------------+

我想获取每年每个月的最后插入值。

所以对于我做的例子,这应该是 Select 的输出:

+-----------+------------+---------------------+
| change_id | emp_salary | change_date |
+-----------+------------+---------------------+
| 2 | 700.00 | 2018-06-25 15:20:30 |
| 3 | 300.00 | 2018-07-02 12:17:17 |
+-----------+------------+---------------------+

1 won't appear because is an outdated version of 2

最佳答案

您可以使用自联接来选择分组最大行,在内部查询中通过对数据按月和按年分组来选择 change_date 的最大值

select t.*
from your_table t
join (
select max(change_date) max_change_date
from your_table
group by date_format(change_date, '%Y-%m')
) t1
on t.change_date = t1.max_change_date

Demo

如果您可以使用支持窗口函数的 Mysql 8,您可以使用通用表表达式和 rank() 函数来选择每年和每月 change_date 最高的行

with cte as(
select *,
rank() over (partition by date_format(change_date, '%Y-%m') order by change_date desc ) rnk
from your_table

)

select * from cte where rnk = 1;

Demo

关于mysql - 从 DATETIME 中选择每年每个月的最后插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51378339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com