当您更改一组empID,DepID时,结果列应增加1。如果连续2行的某些DT之间的天数大于5天,则结果列也应重置。
libs
答案 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)
我可能觉得太复杂了。嗯,这是我的方法:
以下是查询:
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
)
);