根据每个 customerID 的另一列中的值重置 运行 总数 - SQL 服务器

Resetting Running Total based on value in another column per customerID - SQL Server

我已经尝试在此处寻找此问题的答案,虽然找到了类似的查询,但我还没有找到确切的答案。

我正在计算客户获得特定分数的实例,如果他们得到的分数低于该分数,我希望重置计数。

这是我的数据:

这是我想要产生的结果:

任何帮助,以及对所用高级代码的解释,我们将不胜感激。

您可以根据值小于阈值的次数来定义一个组。这定义了每个组。在那之后,你想要一个行号:

select t.*,
       (case when t.score < 1 then 0
             else row_number() over (partition by t.customerId, grp, score order by t.attempt)
        end) as ranking
from (select t.*,
             sum(case when score < 1 then 1 else 0 end) over (partition by t.customerId order by t.attempt) as grp
      from t
     ) t;

Here 是一个 db<>fiddle.

DECLARE @T table (CustomerID int, Attempt int, score decimal(10,2) )
INSERT INTO @T
VALUES
(111, 1, 1)
,(111, 2, 1)
,(111, 3, 1)
,(111, 4, 0.5)
,(111, 5, 1)
,(111, 6, 0)
,(222, 5, 0.5)
,(222, 6, 1)
,(222, 7, 0.5)
,(222, 8, 1)
,(222, 9, 1)
,(222, 110, 1)
select t.*,
   (case when t.score < 1 then 0
         else row_number() over (partition by t.customerId, grp order by t.attempt)
    end) as ranking
from (select t.*,
         sum(case when score < 1.00 then 1 else 0 end) over (partition by t.customerId order by t.attempt) as grp
  from @t t
 ) t;