I have one table of user history with a start and end date. I have a second table of role history with a start and end date.
I'm trying to take the user history table and break it up with the role history. Basically, I'm trying to map the role history to the user history.
For example:
Here is the user table
| person | title | roleid | start | end |
|--------|-------------|--------|-----------|-------------|
| a | VP | 1 | 10/1/2017 | 10/31/2017 |
| a | Director | NULL | 11/1/2017 | 11/25/2017 |
| a | NULL | 2 | 11/26/2017| 12/5/2017 |
| a | President | 3 | 12/6/2017 | 12/31/2017 |
| a | Exec | 3 | 01/01/2018| 12/31/2999 |
and the role history table
| roleid | role | xxxxxx | start | end |
|--------|-------------|--------|------------|-------------|
| 1 | Champion | x | 10/05/2017 | 11/01/2017 |
| 2 | Nerd | x | 10/20/2017 | 12/31/2999 |
| 3 | Peon | x | 11/26/2017 | 12/15/2017 |
| 3 | King | x | 12/16/207 | 12/31/2017 |
I'm trying to get this type of result:
| person | title | role_id | role | start | end |
|--------|-------------|---------|--------|------------|-------------|
| a | VP | NULL |NULL | 10/01/2017 | 10/04/2017 |
| a | VP | 1 |champion| 10/05/2017 | 10/31/2017 |
| a | Director | NULL |NULL | 11/01/2017 | 11/25/2017 |
| a | NULL | 2 |nerd | 11/26/2017 | 12/05/2017 |
| a | President | 3 |peon | 12/06/2017 | 12/15/2017 |
| a | President | 3 |King | 12/16/2017 | 12/31/2017 |
| a | Exec | 3 |King | 01/01/2018 | 12/31/2999 |
I tried approaching this with multiple insert statements but I keep getting the logic wrong. Any help would be appreciated.
First: I create virtual primary key in the 'user table' by row_number function like below.
Using above table i pretend it as 'temptable' to got which row by vkey we have to join 'role history table':
After got the vkey we can join 'role history table' to get the result you want.(I pretend above table as 'keytable'):