I have the employee data like this:
| ID | previous_org | new_org | event | event_date |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 1 | | A | Hire | 202201 |
| 1 | A | B | Transfer | 202207 |
| 1 | | B | Retired | 202301 |
| 2 | | A | Hire | 202201 |
| 2 | A | B | Transfer | 202207 |
| 2 | B | C | Transfer | 202301 |
| 2 | | C | Retired | 202308 |
I want to add two columns to above data and manage it as historical data.
The columns I want to add are start_date
and end_date
.
It is difficult to explain what I want to do, so I will show the desired result below.
| ID | previous_org | new_org | event | event_date | start_date | end_date |
| ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
| 1 | | A | Hire | 202201 | 202201 | 202206 |
| 1 | A | B | Transfer | 202207 | 202207 | 202212 |
| 1 | | B | Retired | 202301 | 202301 | |
| 2 | | A | Hire | 202201 | 202201 | 202206 |
| 2 | A | B | Transfer | 202207 | 202207 | 202212 |
| 2 | B | C | Transfer | 202301 | 202301 | 202307 |
| 2 | | C | Retired | 202308 | 202308 | |
The start_date
column contains the date in the event_date
column of the row.
The end_date
column contains the date one month before the date in the event_date
column for the next event.
Calculations must be made for each employee.
Can I get this result with SQL Server?
I understand that this can be accomplished using something other than SQL Server, but in this case I must use SQL Server.
Any answer would be helpful.
Thank you.
1条答案
按热度按时间sqyvllje1#
Code:
This code uses a
CTE
to derive theed
column (temporary column) as the nextevent_date
using theLEAD
function. Then, it calculates theenddate
column by concatenating theed
column with'01'
to get the complete date formatyyyyMMdd
, and then it is casted to adate
data type. ThenDATEADD
- is used to substract one month from the derived value. Later, it formats as a string in the'yyyyMM'
format using theFORMAT
function.demo