简体   繁体   中英

SQL Join two tables using versioned data

I have two tables, both of which have a record date as part of the key. When the record is edited, a new version of it with the current RecordDate and whatever other changes were made is created. This applies to both tables. The RecordDate is not used as a foreign key at all only applies to its own table.

So for this example, Kate gets married, her employee record is updated to reflect her new surname. She is also taken off the fish counter and given a cushy job in management and so her Employee Task also changes.

Employee
CompanyId EmployeeId RecordDate Name
1         1          2011/04/11 Kate Windsor
1         1          2010/07/04 Kate Middleton

EmployeeTasks
CompanyId EmployeeId RecordDate TaskId TaskCode
1         1          2015/09/18 1      bbb
1         1          2015/09/18 1      aaa

I can select the most recent set of records for a single table, I can join one of these tables with another non versioned table but what I cannot figure out how to do is to join both these tables together such that I get data for the most recent records for each, so that it would return something like this?

CompanyId EmployeeId Name         TaskId TaskCode
1         1          Kate Windsor 1      bbb

FWIW Im using an Oracle DB.

It's a bit messy, but you need to get down to just the employee and company IDs with a max record date for each. With the MAX date from each table those can be used to join back to the base tables and pull only the related records.

SELECT e.companyID, e.employeeID, 
    FROM (SELECT companyID, employeeID, MAX(RecordDate) AS maxDate
        FROM employee 
        GROUP BY companyID, employeeID
    ) e
    INNER JOIN (SELECT companyID, employeeID, MAX(RecordDate) AS maxDate
        FROM employeeTasks
        GROUP BY companyID, employeeID
        ) et ON e.companyID = et.companyID AND e.employeeID = et.employeeID
    INNER JOIN employee emp 
        ON e.companyID = emp.companyID AND e.employeeID = emp.employeeID AND emp.RecordDate = e.maxDate
    INNER JOIN employeeTask oN empT 
        ON et.companyID = empT.companyID AND et.employeeID = empT.employeeID AND empT.RecordDate = et.maxDate

Sorry for the initial, incomplete post, my fingers got away from me and accidentally submitted too soon!

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