I'm trying to create a SCD type 2 from the table below using SQL.
click on table for better visibility if neededAs shown, The table has daily records for each employee. I want to create a type 2 that will contain an effective date and expiration date.
Is the easiest way to do this, using SQL, by using a MERGE? if so, how would I go about it in a way that retains the integrity of the data?
Thank you for any help!
EDIT:
I was not given a specified target table however I believe my following table should look like the following:
click on table for better visibility if neededI also think another possibility would be to utilize the LEAD() and LAG() functions to achieve the result but after implementing the following code, I am very close to my desired result, but not quite what I'm needing. My code and resulting table is below:
SELECT employee_id, name, manager_id,
CASE
WHEN LAG(manager_id) OVER() != manager_id THEN e.date
WHEN e.date = FIRST_VALUE(e.date) OVER() THEN e.date
ELSE NULL
END as "Effective Date",
CASE
WHEN LEAD(manager_id) OVER() != manager_id THEN LEAD(e.date) OVER()
ELSE NULL
END as "Expiration Date"
FROM employee e
(click on table for better visibility if needed)