简体   繁体   English

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

[英]Select last inserted value of each month for every year from DATETIME

I got a DATETIME to store when the values where introduced, like this example shows: 我有一个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)
);

I gonna fill the example like this: 我将填写以下示例:

+-----------+------------+---------------------+
| 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 |
+-----------+------------+---------------------+

I want to get the last inserted value of each month for every year. 我想获得每年每个月的最后插入值。

So for the example I made, this should be the output of the Select: 因此,对于我所做的示例,这应该是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 由于2的版本过旧,因此不会出现1

You could use a self join to pick group wise maximum row, In inner query select max of change_date by grouping your data month and year wise 您可以使用自change_date来选择分组明智的最大行,在内部查询中,通过按月和年分组数据,选择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 演示

If you could use Mysql 8 which has support for window functions you could use common table expression and rank() function to pick row with highest change_date for each year and month 如果您可以使用支持窗口函数的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 演示

The below query should work for you. 以下查询将为您工作。 It uses group by on month and year to find max record for each month and year. 它使用按月和年分组,以查找每个月和年的最大记录。

SELECT s1.*
FROM salary s1
INNER JOIN (
    SELECT MAX(change_date) maxDate
    FROM salary
    GROUP BY MONTH(change_date), YEAR(change_date)
) s2 ON s2.maxDate = s1.change_date;

Fiddle link : http://sqlfiddle.com/#!9/1bc20b/15 小提琴链接: http ://sqlfiddle.com/#!9/1bc20b/15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM