SQL中不同值之间的第一个更改值

时间:2018-08-13 16:43:05

标签: sql oracle11g

我在历史记录表中有5列,每次创建新记录时都会更改特定ID_ 256的借贷状态:

 hist_id    Status   Changed_by  Loan_no    ID_
 1         Active     X          123456    256
 2         Inactive   Y          123456    256
 3         Active     Z          123456    256
 4         Active     K          123456    256
 5         Inactive   L          123456    256

我在主表中有3列(当前存储)

Status   Changed_by  Loan_no    ID_
Inactive   L          123456    256

问题:

我想要第一次更改贷款123456特定ID_的状态的用户名(Changed_By)?

答案应为(是谁先将状态从有效更改为无效):

2         Inactive   Y          123456    256

2 个答案:

答案 0 :(得分:0)

我不确定这是否是解决您问题的最佳解决方案,但它可以达到目的:

select h2.* from history h1
inner join  history as h2  on h2.Loan_no = h1.Loan_no and h2.hist_id = h1.hist_id + 1
where h1.Loan_no = 123456
and h2.status != h1.status
limit 1

要查看所有更改了123456号贷款ID状态的记录,请删除限制,如下所示:

select h2.* from history h1
inner join  history as h2  on h2.Loan_no = h1.Loan_no and h2.hist_id = h1.hist_id + 1
where h1.Loan_no = 123456
and h2.status != h1.status

答案 1 :(得分:0)

以下是使用ROW_NUMBER()而非联接的替代解决方案:

SELECT ChangeLog.Changed_by
FROM (SELECT hist.*, ROW_NUMBER() OVER(PARTITION BY hist.ID_ ORDER BY hist.hist_id) Change_Num
FROM dbo.history hist) ChangeLog
WHERE ChangeLog.Change_Num = 2 AND ChangeLog.ID_ = 256

这也假定对给定ID进行历史记录计时的最佳方法是在hist_id列上排序。如果您的架构包含一个更好的列来确定年代,则可以将ORDER BY hist.hist_id替换为ORDER BY hist.<better_column>