sql如何根据时间取出最新的数据记录

1-如何根据时间取出最新的数据记录

例子:table1 :
userCode   name            datetime
107        tom            2017/6/21 22:34
107        tom            2017/6/24 10:21
107   tom            2017/12/7 10:45
107   tom            2017/1/15 14:01
107   tom           2017/12/26 14:11
208   jack            2017/6/21 22:36
208   jack          2017/11/15 10:46
208   jack            2017/1/19 9:12
208   jack            2017/1/10 13:57
208   jack           2017/1/22 10:08
309   ben           2017/6/22 12:54
309   ben           2017/3/11 9:16
309   ben           2017/1/10 11:18
309   ben           2017/12/20 15:09

方法一、not exists

select a.*
from table1 a
where not exists(select 1
from table1 b
where b.name=a.name and b.datetime>a.datetime);

方法二、行号标记法

select   *  
from (SELECT *
    ,row_number() over(partition by  userCode order by datetime desc) as lastIndexCreated  
FROM
    table1   
) t where lastIndexCreated=1;

*最靠谱的为方法二,因为如果创建时间一样,其它两种方法则查询不出数据来


select 1 from table ---查询符合条件的记录的行数

方法三、

或者:

SELECT
a.*
FROM
table1 a
WHERE   
( SELECT count(id) FROM table1 b WHERE b.NAME = a.NAME AND b.datetime > a.datetime )=0;

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐