如何获得每个月的最后日期

时间:2018-07-26 12:21:39

标签: mysql group-by

正如标题所述,我想从每个月中选择一个具有最新日期的记录。 我有一张这样的桌子:

ID  field1          field2          created_at
----------------------------------------------
1   40000.0000      70000.0000      2018-01-31
2   80000.0000      90000.0000      2018-02-28
3   10000.0000      30000.0000      2018-03-31
4   12000.0000      32000.0000      2018-04-30
5   212500.0000     312500.0000     2018-05-31
6   324000.0000     424000.0000     2018-06-30
7   122300.0000     222300.0000     2018-07-26
8   357772.2420     307600.9081     2018-07-31

我提出了这个查询,但是它没有按预期工作。

  

SELECT id,field1,field2,MAX(created_at)AS   created_at来自my_table GROUP BY   YEAR(created_at),MONTH(created_at)ORDER BY created_at ASC

我得到的输出:

ID  field1          field2          created_at
----------------------------------------------
1   40000.0000      70000.0000      2018-01-31
2   80000.0000      90000.0000      2018-02-28
3   10000.0000      30000.0000      2018-03-31
4   12000.0000      32000.0000      2018-04-30
5   212500.0000     312500.0000     2018-05-31
6   324000.0000     424000.0000     2018-06-30
7   122300.0000     222300.0000     2018-07-31   <-- values from ID 7 but date from ID 8

预期产量

ID  field1          field2          created_at
----------------------------------------------
1   40000.0000      70000.0000      2018-01-31
2   80000.0000      90000.0000      2018-02-28
3   10000.0000      30000.0000      2018-03-31
4   12000.0000      32000.0000      2018-04-30
5   212500.0000     312500.0000     2018-05-31
6   324000.0000     424000.0000     2018-06-30
8   357772.2420     307600.9081     2018-07-31

如何从与MAX(created_at)相同的记录中选择值?

SQLFiddle

2 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

SELECT id, field1, field2, created_at AS created_at 
FROM `my_values` 
where created_at in (select max(created_at)
                 FROM `my_values` 
 GROUP BY YEAR(created_at), MONTH(created_at) ORDER BY created_at ASC )

See SQLFiddle

答案 1 :(得分:1)

通过加入

select id, field1, field2,T2.created_at from my_values T1 
inner join 
(
select max(created_at) as created_at
                 FROM `my_values` 
 GROUP BY YEAR(created_at), MONTH(created_at) ORDER BY created_at ASC
 ) as T2
 on T1.created_at=T2.created_at

http://sqlfiddle.com/#!9/4f7442/18

id  field1  field2  created_at
1   40000   70000   2018-01-31
2   80000   90000   2018-02-28
3   10000   30000   2018-03-31
4   12000   32000   2018-04-30
5   212500  312500  2018-05-31
6   324000  424000  2018-06-30
8   357772.242  307600.9081 2018-07-31