Sql 查找员工所在部门的变动次数
我在下表中存储了员工的任何更新:Sql 查找员工所在部门的变动次数,sql,sql-server,tsql,Sql,Sql Server,Tsql,我在下表中存储了员工的任何更新: EmployeeId DepartmentId Status From To 44 30 Recruited 01/01/2017 06/03/2017 44 56 IN 07/03/2017 07/03/2018 44 67 IN 06/05/2018 06/09/2018 44
EmployeeId DepartmentId Status From To
44 30 Recruited 01/01/2017 06/03/2017
44 56 IN 07/03/2017 07/03/2018
44 67 IN 06/05/2018 06/09/2018
44 33 IN 07/09/2018 02/02/2019
44 33 OUT 03/02/2019 31/12/2019
44 45 Recruited 01/02/2020 03/02/2020
44 45 IN 04/02/2020 NULL
我想计算一下,在知道员工生命周期如下所示的情况下,每个员工更换部门的次数:重复输入输出
然后离开公司的员工又回到了公司,就像这个例子一样。我不确定招聘、入职和离职与此有什么关系。如果每一行表示员工在某个部门工作的一段时间,则使用滞后来衡量变化:
select employeeId, count(*)
from (select t.*,
lag(departmentId) over (partition by employeeId order by from_date) as prev_departmentId
from t
) t
where prev_departmentId is null or prev_departmentId <> departmentId
group by employeeId;
这个员工的答案是什么?他换了5次部门,离开了公司,然后又回到了公司。