I have a database where most of the tables have System-Versioned Temporal Tables (history tables). Often I want to query rows from the 'normal' table and get some data from the oldest record in the history table for each row in the normal table, e.g. the create timestamp and create UserId. Is there any shortcut to doing this or is something like this the right approach:
My tables are:
dbo.Employee
- primary key isEmployeeId
, period cols areSysStartTime
,SysEndTime
dbo.Employee_History
Query:
select
-- All columns from normal table:
e.*
-- Plus columns wanted from history table:
, created.SysStartTime as CreatedTime
, created.EditUserId as CreatedUserId
from dbo.Employee e
-- Join to a derived table with the original rows for each record.
-- If a record in the normal table hasn't been changed there won't be a row in this.
left join (
select *
from (
select EmployeeId
, SysStartTime
, EditUserId
, RowVersionNumber = ROW_NUMBER() over ( partition by EmployeeId order by SysStartTime asc )
from Employee_History
) h
-- filter to only get the oldest of each record
where RowVersionNumber = 1
) created on u.EmployeeId = created.EmployeeId