这个问题对我来说很难写出来。
我有一个表,如下所示:
<表类>
日期
ItemNumber
FlagA
FlagB
tbody><<tr>2020-01-01 101 Y N 2020-01-02 101 N N 2020-01-03 101 Y N 2020-01-04 101 Y N 2020-01-05 101 Y Y 2020-01-01 102 Y N 2020-01-02 102 N N 2020-01-03 102 N N 2020-01-04 102 Y Y 表类>
您似乎需要flagA = Y
的最近不间断序列的枚举。那就是:
select t.*,
(case when grp = 0 and flagA = 'Y'
then row_number() over (partition by grp, flagA order by date)
else 0
end) as runningCount
from (select t.*,
sum(case when flagA = 'N' then 1 else 0 end) over (partition by itemNumber order by date desc) as grp
from t
) t;