How to get date range between dates from the records in the same table?

Viewed 30

I have a table with employment records. It has Employee code, status, and date when table was updated. Like this:

Employee Status Date
001 termed 01/01/2020
001 rehired 02/02/2020
001 termed 03/03/2020
001 rehired 04/04/2021

Problem - I need to get period length when Employee was working for a company, and check if it was less than a year - then don't display that record.

There could be multiple hire-rehire cycles for each Employee. 10-20 is normal. So, I'm thinking about two separate selects into two tables, and then looking for a closest date from hire in table 1, to termination in table 2. But it seems like overcomplicated idea.

Is there a better way?

1 Answers

Many approaches, but something like this could work:

SELECT
    Employee,
    SUM(DaysWorked)
FROM
(
    SELECT
        a1.employee,
        IsNull(DateDiff(DD, a1.[Date], 
            (SELECT TOP 1 [Date] FROM aaa a2 WHERE a2.employee = a1.employee AND  a2.[Date] > a1.[Date] and [status] <> 'termed' ORDER BY [Date] )
            ),DateDiff(DD, a1.[Date], getDate())) as DaysWorked
    FROM
        aaa a1
    WHERE
        [Status] = 'termed'
) Totals
GROUP BY
    Totals.employee
HAVING SUM(DaysWorked) >= 365

Also using a CROSS JOIN is an option and perhaps more efficient. In this example, replace 'aaa' with the actual table name. The IsNull deals with an employee still working.

Related