我有一个数据集的快照,如下所示:
effective_date hire_date name job_level direct_report
01.01.2018 01.01.2018 xyz 5 null
01.02.2018 01.01.2018 xyz 5 null
01.03.2018 01.01.2018 xyz 5 null
01.04.2018 01.01.2018 xyz 6 null
01.05.2018 01.01.2018 xyz 6 null
01.01.2018 01.02.2018 abc 5 null
01.02.2018 01.02.2018 abc 5 null
01.03.2018 01.02.2018 abc 5 null
01.04.2018 01.02.2018 abc 5 null
01.05.2018 01.02.2018 abc 5 null
我想了解在整个时间内有多少员工从第5级搬到/升级到第6级?
答案 0 :(得分:1)
这是一种使用两级聚合的方法。您可以通过比较" 5"的最短日期来获得晋升的员工。到" 6"的最大日期:
select name
from t
where job_level in (5, 6)
group by name
having min(case where job_level = 5 then effective_date end) < max(case where job_level = 6 then effective_date end);
计算它们:
select count(*)
from (select name
from t
where job_level in (5, 6)
group by name
having min(case where job_level = 5 then effective_date end) < max(case where job_level = 6 then effective_date end)
) x;
或者,您可以使用lag()
:
select count(distinct name)
from (select t.*, lag(job_level) over (partition by name order by effective_date) as prev_job_level
from t
) t
where prev_job_level = 5 and job_level = 6;
两者略有不同,但在问题含糊不清的范围内。例如,第一个将计数5 - >; 4 - &gt; 6,第二个不会。
答案 1 :(得分:1)
你可以试试这个。
select count(distinct name) from employees e1
WHERE effective_date between '01.01.2018' and '01.05.2018'
And job_level = 5
and EXISTS (select * from employees e2 where e1.name = e2.name
and e2.effective_date > e1.effective_date
and e2.job_level = 6
)