根据每个客户ID的另一列中的值重置运行总计-SQL Server

时间:2018-12-19 18:44:06

标签: sql sql-server ranking running-total

我已经尝试在这里寻找该问题的答案,尽管找到了类似的查询,但我没有找到确切的查询。

我希望对获得一定分数的客户实例进行计数,如果他们获得的分数小于该分数,我希望重置该计数。

这是我拥有的数据:

Data Before Running Total

这是我想产生的结果:

With Running Total

任何帮助以及使用的任何高级代码的解释都将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以根据值小于阈值的次数来定义组。定义每个组。之后,您需要一个行号:

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 <>小提琴。

答案 1 :(得分:0)

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;