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

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bingo_BIG

你的鼓励是我最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值