我想要一个查询来生成下面的结果列。假设所需的列存在于同一个表中

时间:2016-06-02 10:39:14

标签: sql oracle

当您更改一组empID,DepID时,结果列应增加1。如果连续2行的某些DT之间的天数大于5天,则结果列也应重置。

libs

2 个答案:

答案 0 :(得分:0)

我想你想要row_number()。但是,大于5天的情况"很棘手您还需要识别行组。为此,使用lag()查找组开始的时间。然后是累计和来指定组,最后是row_number()

select EmpID, DepID, someDt,
       row_number() over (partition by EmpID, DepId, grp, order by someDt) as Result
from (select t.*,
             sum(case when someDt < prevDt + 5 then 0 else 1 end) over
                 (partition by EmpID, DepId order by someDt) as grp
      from (select t.*,
                   lag(someDt) over (partition by EmpID, DepId order by someDt) as prevDt
            from t
           ) t
     ) t;

答案 1 :(得分:0)

我可能觉得太复杂了。嗯,这是我的方法:

  1. 检测所需的群组中断记录;用1标记它们,而其他记录得到0
  2. 在该分组中断号上有一个总计,因此您会得到编号组
  3. 为每组记录编号。
  4. 以下是查询:

    select 
      empid,
      depid,
      somedt, 
      row_number() over (partition by grp order by empid, depid, somedt) as result
    from
    (
      select 
        empid, depid, somedt, sum(chg) over (order by empid, depid, somedt) as grp
      from
      (
        select 
          empid, depid, somedt,
          case when empid = lag(empid) over (order by empid, depid, somedt)
                and depid = lag(depid) over (order by empid, depid, somedt)
                and somedt <= lag(somedt) over (order by empid, depid, somedt) + 5
               then 0
               else 1
          end as chg
        from mytable
      )
    );