How to get latest record of a username by latest date in sql

时间:2018-11-14 08:44:20

标签: sql

I want to process the all the data in database and if username has the same value, I need to get the latest status(which is the group_codes) based on the T_Date. e.g.

usernames |  group_codes | Fr_Date | T_Date
ABC          PT           2016-07    2016-08
AAA          FT           2015-08    2016-08
ABC          FT           2018-09    2018-10

So output be like:

ABC       FT          2018-09              2018-10 

(This data has two values but with the latest data)

AAA       FT          2015-08              2016-08

Current code is:

select usernames, max(T_Date)
from AA_WC_tempstatus
group by usernames

2 个答案:

答案 0 :(得分:1)

使用corealted子查询

select t.* from table_name t where 
t.T_Date= ( select max(T_Date) 
      from table_name t1 where t1.usernames=t.usernames
          )

或窗口函数(大多数dbms支持)

select * from 
(

select * ,row_number() over(partition by usernames order by T_Date desc) rn
  from table_name
) t where rn=1

答案 1 :(得分:0)

使用相关子查询

select usernames, T_Date from AA_WC_tempstatus a
where exists (select  1 from AA_WC_tempstatus b where a.username=b.username
having max(b.T_Date)=a.T_Date)

或者您可以使用row_number()

select * from 
( 
 select *, row_number() over(partition by username order by t_Date desc) as rn from 
 AA_WC_tempstatus 
)A where rn=1