[英]how to get latest date data from table
I want to get rows of the latest date and the next latest date. 我想获取最新日期和下一个最新日期的行。 I have searched lots of sites and I have still no idea how to write the sql statement.
我搜索了很多站点,但我仍然不知道如何编写sql语句。
From this 由此
id inputDate refNo
1 2016-09-22 16092201820X0X
2 2016-09-22 16092200230X1X
3 2016-09-22 16092200810X3X
4 2016-09-21 16092200430X2X
5 2016-09-21 16092201460X7X
6 2016-09-21 16092200430X1X
7 2016-09-20 16092202260X3X
8 2016-09-20 16092200330X6X
9 2016-09-20 16092200610X3X
10 2016-09-19 16092200430X8X
11 2016-09-19 16092200450X1X
to this 对此
id inputDate refNo
1 2016-09-22 16092201820X0X
2 2016-09-22 16092200230X1X
3 2016-09-22 16092200810X3X
4 2016-09-21 16092200430X2X
5 2016-09-21 16092201460X7X
6 2016-09-21 16092200430X1X
In ANSI standard SQL, you would use dense_rank()
: 在ANSI标准SQL中,您可以使用
dense_rank()
:
select t.*
from (select t.*, dense_rank() over (order by inputdate desc) as seqnum
from t
) t
where seqnum <= 2;
MySQL does not support the ANSI-standard window functions (unlike basically all other major databases). MySQL不支持ANSI标准的窗口函数(基本上与所有其他主要数据库不同)。
In MySQL, this is trickier. 在MySQL中,这比较棘手。 Here is a convenient method:
这是一个方便的方法:
select t.*
from t join
(select inputdate
from (select distinct inputdate from t) t
order by inputdate desc
limit 2
) tt
on t.inputdate = tt.inputdate;
You don't actually need the second subquery, so you can do: 您实际上不需要第二个子查询,因此可以执行以下操作:
select t.*
from t join
(select distinct inputdate
from t
order by inputdate desc
limit 2
) tt
on t.inputdate = tt.inputdate;
But it can be confusing to remember whether select distinct
happens before or after the order by
. 但是,记住
select distinct
order by
在之前还是之后发生,可能会造成混淆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.