简体   繁体   English

如何为DATE分组的MAX DATE在mysql中选择相应的列

[英]How to select a corresponding column in mysql for a MAX DATE grouped by DATE

mysql table: stats mysql表:统计

columns: 
         date           | stats
05-05-2015 22:25:00     | 78
05-05-2015 09:25:00     | 21
05-05-2015 05:25:00     | 25
05-04-2015 09:25:00     | 29
05-04-2015 05:25:00     | 15

sql query: sql查询:

SELECT MAX(date) as date, stats FROM stats GROUP BY date(date) ORDER BY date DESC

when I do this, I does select one row per date (grouped by date, regardless of the time), and selects the largest date with MAX , but it does not select the corresponding column. 这样做时,确实会为每个日期选择一行(按日期分组,而不考虑时间),并使用MAX选择最大的日期,但不会选择相应的列。 for example, it returns 05-05-2015 22:25:00 as the date , and 25 as the stats . 例如,它返回05-05-2015 22:25:00作为date ,并返回25作为stats It should be selecting 78 as the stats . 应该选择78作为stats I've done my research and seems like solutions to this are out there, but I am not familiar with JOIN or other less-common mysql functions to achieve this, and it's hard for me to understand other examples/solutions so I decided to post my own specific scenario. 我已经进行了研究,似乎可以找到解决方案,但是我不熟悉JOIN或其他不太常见的mysql函数来实现此目的,而且我很难理解其他示例/解决方案,因此我决定发布我自己的特定情况。

This question is asked every single day in SO. 在SO中每天都会问这个问题。 Sometimes, it's correctly answered too. 有时,它也被正确回答。 Anyway, purists won't like it but here's one option: 无论如何,纯粹主义者不喜欢它,但这是一个选择:

Select x.* from stats x join (SELECT MAX(date) max_date FROM stats GROUP BY date(date)) y on y.max_date = x.date;

Obviously, for this to work dates need to be stored using a datetime data type. 显然,为此,需要使用datetime数据类型存储日期。

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

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