我已经尝试在这里寻找这个问题的答案,尽管我找到了类似的查询,但我还没有找到确切的答案。
我希望对客户获得某个分数的实例进行计数,如果他们得到的分数小于该分数,我希望该计数被重置。
这是我拥有的数据:
这是我想要产生的结果:
任何帮助,以及任何使用的高级代码的解释都将不胜感激。
发布于 2018-12-20 03:46:52
您可以根据值小于阈值的次数来定义组。定义了每一组。在此之后,您需要一个行号:
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。
发布于 2018-12-20 18:57:33
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;
https://stackoverflow.com/questions/53857418
复制相似问题