0

I have below data set in SQL Server and I need to select the data with conditions in order below:

First, check to see if date_end is 1/1/2099, then select the row that has smallest days gap and skill_group is not SWAT for rows have same employee_id, in this case that is row 2.

Second, for rows that do not have 1/1/2099 date_end, select row that has most recent day date_end, in this case it's row 4.

ID  employee_id last_name   first_name  date_start  date_end    skill_group
---------------------------------------------------------------------------
1   N05E0F  Mike    Pamela  12/19/2013  1/1/2099    SWAT
2   N05E0F  Mike    Pamela  9/16/2015   1/1/2099    Welcome Team
3   NSH8A   David   Smith   12/19/2013  9/16/2016   Unlicensed
4   NSH8A   David   Smith   8/16/2015   10/16/2016  CMT

1 Answer 1

1

There are many ways to do this. Here are some of them:

top with ties version:

select top 1 with ties
    *
  from tbl
  where skill_group != 'SWAT'
  order by 
    row_number() over (
      partition by employee_id
      order by date_end desc, datediff(day,date_start,date_end) asc 
      )

with common_table_expression as () using row_number() version:

with cte as (
  select  *
      , rn = row_number() over (
              partition by employee_id
              order by date_end desc, datediff(day,date_start,date_end) asc 
            )

    from tbl
    where skill_group != 'SWAT'
)
select *
  from cte
  where rn = 1

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.