[英]MYSQL get records group by date desc and order by date asc
I've a mysql table with below data.我有一个包含以下数据的 mysql 表。
name table_data table_date
name1 {count:2} 2020-01-24 02:23:41
name1 {count:5} 2020-01-24 05:45:07
name1 {count:8} 2020-01-24 12:45:18
name1 {count:20} 2020-01-30 08:40:07
name1 {count:28} 2020-01-30 15:08:12
I want a sql for getting the only one record for a date.我想要一个 sql 来获取日期的唯一记录。 The problem is that, I've to order the table based on table_date asc but need only the latest record for each date.
问题是,我必须根据 table_date asc 对表进行排序,但只需要每个日期的最新记录。
Expected result:预期结果:
name table_data table_date
name1 {count:8} 2020-01-24 12:45:18
name1 {count:28} 2020-01-30 15:08:12
My sql is like:我的 sql 是这样的:
select name, table_data, table_date
from my_table
where DATE(table_date) <= DATE('2020-04-01') group by DATE(table_date) order by table_date asc
But this SQL will only give the record with minimum date.但是这个 SQL 只会给出最小日期的记录。
Can anyone help me solve this?谁能帮我解决这个问题?
Thanks in advance.提前致谢。
You don't mention the MySQL version you are using.你没有提到你正在使用的 MySQL 版本。 In MySQL 8.x you can use
ROW_NUMBER()
to decide which rows to keep.在 MySQL 8.x 中,您可以使用
ROW_NUMBER()
来决定要保留哪些行。
For example:例如:
select name, table_date
from (
select name, table_date
row_number() over partition by name order by table_date desc) as rn
from my_table
) x
where rn = 1
I think in MySQL 5.x you can use IN
with tuples.我认为在 MySQL 5.x 中,您可以将
IN
与元组一起使用。 For example:例如:
select *
from my_table
where (name, table_date) in (
select name, max(table_date) from my_table group by name, date(table_date)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.