【问题标题】:SQL - find most recent promotion dateSQL - 查找最近的促销日期
【发布时间】:2017-05-04 10:00:26
【问题描述】:

假设我有一个表“EmployeePromotions”,其中的数据类似于:

Job_Title      Job_Description      Name          Effective_Date
DM1            Manager              John Doe      12/01/2016
AM1            Manager              John Doe      01/12/2015
ASM            Assist Manager       John Doe      10/01/2014
MG1            Manager              John Doe      07/15/2014       
ASM            Assist Manager       John Doe      03/01/2012
CSV            Service Rep          John Doe      011/21/2010

我希望能够查询并返回 Job_Description 为“Manager”的最短生效日期,而 Job_Description 中没有任何空白。我知道这很令人困惑,例如:

对于 John Doe,我只想返回此记录:

Job_Title      Job_Description      Name          Effective_Date
AM1            Manager              John Doe      01/12/2015

我不希望第一次出现日期为 2014 年 7 月 15 日的“经理”的原因是,他在 2015 年 1 月 12 日被降职,然后再次晋升。我只想要最近的促销日期,在 Job_Description = "Manager" 中没有空白。

Manager 的 Job_Description 附有许多不同的 Job_Title,它们不属于任何特定的层次结构,因此很难根据职位名称预测最近的分组。

【问题讨论】:

  • 好的。所以等级层次结构明智Manager > Assist Manager > Service Rep。这是一个正确的假设吗?
  • 当经理被降职并且再也没有晋升时,您需要什么输出?

标签: sql ssms


【解决方案1】:
select Job_Title,Job_Description,Name,Effective_Date 
from (select t.*
      ,min(case when job_description = 'Manager' then grp end) over(partition by name) as min_mgr_grp
      ,min(effective_date) over(partition by name,grp) as start_date
      from (select t.*
            ,row_number() over(partition by name order by effective_date desc) 
            - row_number() over(partition by name order by job_description,effective_date desc) as grp
            from t
            ) t
     ) t
where job_description = 'Manager' and grp = min_mgr_grp and effective_date = start_Date  
  • 使用不同的行号方法将具有相同 job_description 的连续行分类为给定名称的一组。 (最内层查询)
  • 然后获取 job_description = Manager 的最小组号(根据 Effective_date 降序分配的组)以及最小 Effective_date(该组的 start_date)。 (第二个最里面的查询)
  • 最后选择上面有最小组和 start_date 的行。

Sample Demo

【讨论】:

  • 清晰、简洁并准确地解释了它的作用。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-10
  • 2019-05-31
  • 1970-01-01
  • 1970-01-01
  • 2019-06-30
相关资源
最近更新 更多