T-SQL : 如何 select 有多个条件的行

T-SQL : how to select row with multiple conditions

我在 SQL 服务器中设置了以下数据,我需要 select 具有以下条件的数据:

首先,检查 date_end 是否为 2099 年 1 月 1 日,然后 select 天数间隔最小的行和 skill_group 不是 SWAT,因为行具有相同的 employee_id,在本例中为第 2 行。

其次,对于没有 1/1/2099 date_end 的行,select 具有最近一天 date_end 的行,在本例中是第 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

有很多方法可以做到这一点。以下是其中一些:

top with ties版本:

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()版本:

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