根据 Revision Id 获取历史值

Get the history values based on Revision Id

我有两个 table table,第一个 table 存储所有最新数据,第二个 table 用于捕获更改的数据。例如,如果用户更改值,FIRST table 将更新数据,而 SECOND table 将使用唯一的修订 ID 存储以前的数据和新数据。

问题:如果我想查看修订版 4 的数据,我不确定如何回溯这些值并在那段时间 table 1 中找到确切的数据

DECLARE @Projects TABLE(
    ProjectId int,
    ProjectName VARCHAR(255),
    StartQuarter int,
    EndQuarter int,
    StartYear int,
    EndYear int,
    Description varchar(255)
);

DECLARE @History TABLE(
    ProjectId int,
    RevisionId int,
    Attribute varchar(255),
    Previous varchar(255),
    New varchar(255)
);

INSERT INTO @Projects (ProjectId,ProjectName,StartQuarter,EndQuarter,StartYear,EndYear,Description)
VALUES (1,'P1', 1,4,2022,2022,'Test')

INSERT INTO @History (ProjectId ,   RevisionId ,    Attribute , Previous ,New )
values (1,2,'ProjectName', 'Project 1', 'Projects')
,(1,3,'Description', 'new', 'newtest')
,(1,4,'ProjectName', 'Projects', 'Alpha')
,(1,5,'Description', 'newtest', 'Test')
,(1,6,'ProjectName', 'Alpha', 'P1')

当前,在完成所有更改后,table 看起来像这样:

ProjectId   ProjectName StartQuarter    EndQuarter  StartYear   EndYear   Description
1           P1          1               4           2022        2022      Test

现在我想在 RevisionId = 4 期间查看数据,输出应该如下所示:

ProjectId   ProjectName StartQuarter    EndQuarter  StartYear   EndYear   Description
1           Alpha       1               4           2022        2022      newtest

一种方法是使用外部应用程序

select p.ProjectID,
       isnull(n.New, p.ProjectName) as ProjectName,
       p.StartQuarter,
       p.EndQuarter,
       p.StartYear,
       p.EndYear,
       isnull(d.New, p.Description) as Description
from   @Projects p

  outer apply ( select top 1
                       h.New
                from   @History h 
                where  h.ProjectId = p.ProjectId
                and    h.Attribute = 'ProjectName'
                and    h.RevisionId <= 4
                order by h.RevisionId desc
              ) n

  outer apply ( select top 1
                       h.New
                from   @History h 
                where  h.ProjectId = p.ProjectId
                and    h.Attribute = 'Description'
                and    h.RevisionId <= 4
                order by h.RevisionId desc
              ) d

结果是

ProjectID ProjectName StartQuarter EndQuarter StartYear EndYear Description
1 Alpha 1 4 2022 2022 newtest