简体   繁体   中英

sql self join on previous record for audit change

i am trying to get a sql query to return rows with the status of the previous time there was an audit log for the same account

like

create table aud
(
id int IDENTITY(1,1),
date_time datetime,
[user] varchar(20),
account varchar(20),
[status] char(2)
)
insert into aud values(getdate(),'guy','123456','00')
insert into aud values(getdate(),'guy','123456','01')
insert into aud values(getdate(),'guy','123456','02')
insert into aud values(getdate(),'guy','123456','00')
insert into aud values(getdate(),'guy','123456','04')
insert into aud values(getdate(),'guy','123456','01')

What i am looking for is a result that lists the previous account status something like date_time, user, account, status, previous_status

i tried

select a.*, b.*  from aud a
join aud b 
on a.account = (
select top 1 account from aud  where a.account = b.account and a.id > b.id order by date_time asc
)

but this joins more than just the previous one

If you are using SQL Server 2012+, you can use lag() for a single column. In you case, you want all columns so outer apply is better:

select a.*, aprev.*
from aud a outer apply
     (select top 1 a2.*
      from aud a2
      where a2.account = a.account and a2.id < a.id
      order by id desc
     ) aprev;

This assumes that the id orders the records the same way as date_time . Your logic mixes the two -- I think it is better to stick to only one column for defining the previous record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM