【问题标题】:Counting employees from one job level to another计算从一个工作级别到另一个工作级别的员工
【发布时间】:2018-07-27 17:43:32
【问题描述】:

我有一个数据集的快照如下:

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 级?

【问题讨论】:

  • 你已经尝试了什么?
  • 到目前为止,您是否尝试过任何查询?如果有,请提供。我们很乐意帮助您学习,但 SO 不是代码编写服务。
  • 另外,标记您的 DBMS。语法差异会改变答案。 sql 服务器?mysql?甲骨文?使用权? db2?
  • 您需要查看 OVER 和 PARTITION。您可以通过简单的查询 WHERE job_level = 6 获得所有级别为 6 的用户,但它会给您多个结果。 OVER 和 PARTITION 将允许您对这些行进行排名,以便您可以获得用户第 6 级的第一天(逻辑上当他们被提升时)。只需在谷歌上搜索“ms sql over partition by example”这个短语,然后找到最适合您的示例。
  • 实际上,我只是注意到您想统计有多少人晋升为 6,而不是查看他们何时晋升。很抱歉,但我希望它仍然可以帮助你。

标签: sql count


【解决方案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 --> 6,第二个则不计数。

【讨论】:

  • 感谢 Gordon,这绝对有帮助...我陷入了生效日期条款。
【解决方案2】:

你可以试试这个。

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
           )

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2021-06-16
    相关资源
    最近更新 更多