【问题标题】:T-SQL : how to select row with multiple conditionsT-SQL:如何选择具有多个条件的行
【发布时间】:2017-06-05 22:25:06
【问题描述】:

我在 SQL Server 中有以下数据集,我需要按以下顺序选择具有条件的数据:

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

其次,对于没有 1/1/2099 date_end 的行,选择具有最近一天 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

【问题讨论】:

    标签: sql-server tsql select conditional-statements where


    【解决方案1】:

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

    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 () 使用 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
    

    【讨论】:

    • 感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-01-31
    • 2020-10-26
    • 2018-12-24
    • 2013-03-16
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    相关资源
    最近更新 更多