【问题标题】:Extract employee record based on certain criteria根据特定标准提取员工记录
【发布时间】:2020-07-17 10:25:10
【问题描述】:

我有一个员工数据库,其中包含他们在组织中的工作经历。

样本数据 -

+----+----------+------------+
| ID |   Date   |   Event    |
+----+----------+------------+
|  1 | 20190807 | Hired      |
|  1 | 20191209 | Promoted   |
|  1 | 20200415 | Terminated |
|  2 | 20180901 | Hired      |
|  2 | 20191231 | Terminated |
|  3 | 20180505 | Hired      |
|  3 | 20190630 | Promoted   |
+----+----------+------------+

我想提取晋升后被解雇的员工列表。在上面的例子中,查询应该返回 ID 1。

如果有帮助,我正在使用 SSMS 17。

【问题讨论】:

  • 重要的不是 SSMS 的版本,而是它所连接的 SQL Server 的版本,因为它是执行查询的服务器。

标签: sql ssms-2017


【解决方案1】:

您可以尝试使用 lag()

DEMO

select distinct ID from
(
select *,lag(event) over(partition by id order by dateval) as prevval
from t
)A where prevval='Promoted'

【讨论】:

    【解决方案2】:

    如果你想要立即之后,那么你会使用lag()。如果您想要之后的任何时间,那么您可以使用聚合:

    select id
    from t
    group by id
    having max(case when event = 'Promoted' then dateval end) < max(case when event = 'Terminated' then dateval end);
    

    使用lag(),代码如下:

    select id
    from (select t.*, lag(event) over (partition by id order by dateval) as prev_event
          from t
         ) t
    where prev_event = 'Promoted' and event = 'Terminated';
    

    【讨论】:

      【解决方案3】:

      一个简单的exists 检查也可以解决这个简单的要求。

      DEMO

      select * from table1 a
      where event='Terminated'
      and exists(select 1 from table1 b where a.ID = b.ID  and event='Promoted');
      

      输出:

      ID  date1       event
      1   20191209    Terminated 
      

      我们甚至可以在相关子查询中比较事件日期,如 DEMO 链接所示。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 2021-09-23
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        • 2020-02-19
        • 2018-09-25
        相关资源
        最近更新 更多