This question already has answers here:
SQL select only rows with max value on a column [duplicate]
                                
                                    (27个答案)
                                
                        
                                2年前关闭。
            
                    
如标题所述,我想从每个月中选择一个具有最新日期的记录。
我有一张这样的桌子:

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

最佳答案

您可以尝试以下方法:

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

关于mysql - 如何获得每个月的最后日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51538749/

10-11 01:34