说我有一张桌子" 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
我希望能够使用" Manager"的Job_Description查询并返回最小生效日期。在Job_Description中没有任何空白。我知道这很令人困惑,例如:
对于John Doe,我只想返回此记录:
Job_Title Job_Description Name Effective_Date
AM1 Manager John Doe 01/12/2015
我不希望第一次出现"经理" 2014年7月15日的日期是因为他被降职,然后在2015年12月1日再次晋升。我只希望最近的促销日期在Job_Description ="经理"中没有间隙。
Manager的Job_Description附加了许多不同的Job_Titles,它们不在任何特定的层次结构中,因此很难根据作业标题预测最近的分组。
答案 0 :(得分:3)
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