【问题标题】:Sql query to capture minimum date, max date based on row ordering upto nullSql查询捕获最小日期,基于行排序的最大日期为空
【发布时间】:2020-06-27 15:39:32
【问题描述】:

议程是跟踪资源的雇用和重新雇用方案

empID   emp_Status      CreateDate      end_date
1       active          **2019-02-01**  Null
1       active          2019-02-02      2019-01-04 (Skipped because last day is greater than joining date)
1       active          2019-02-03      Null
1       Terminated      2019-02-04      **2019-02-02**
1       Terminated      2019-02-05      2019-02-02
1       active          2019-02-06      Null

输出应该能够跟踪加入日期和最后一个工作日以及相应的计数

输出:

empID   join_date       last_date       Joining_count
1       2019-02-01      2019-02-02      1
1       2019-02-06      Null            2

我需要在 redshift 或 oracle sql 查询中实现这一点。请帮我解决这个问题。

【问题讨论】:

  • 能不能把create table和insert脚本放给用户试用一下,写出来帮助你,太浪费时间了。

标签: sql database oracle amazon-redshift amazon-rds


【解决方案1】:

如果我理解正确,对于每个“新”活动,您想要下一个“终止”。一种方法是创建反向计数的组,然后聚合:

select empid,
       min(case when emp_status = 'active' then createdate end) as active_date,
       min(case when emp_status = 'Terminated' then createdate end) as terminate_date,
       row_number() over (partition by empid order by min(createdate)) as joining_count
from (select t.*,
             sum(case when emp_status = 'Terminated' then 1 else 0 end) over (partition by empid order by createdate desc) as grp
      from t
     ) t
group by empid, grp
having sum(case when emp_status = 'active' then 1 else 0 end) > 0;

Here 是一个 dbfiddle。

【讨论】:

  • 行中有多个终止和活动值,这实际上给出了第一行输出而不是第二行仪式。
  • @SuhasC 。 . .出于某种原因,您将'Terminated' 大写而不是'active',这就是结果集中只有一行的原因。还有另一个,但添加了一个额外的行,但我也修复了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 2015-02-22
  • 2014-08-04
  • 2019-02-09
相关资源
最近更新 更多