SSMS基于值的滚动计数,当值重置为0时

huangapple go评论65阅读模式
英文:

SSMS rolling count based on value resetting at 0

问题

尝试获取一个滚动计数,当值为0时重置。

只需要一些字段。

  • 按日期字段和然后ref字段排序
  • 当值从0变为>0时,计数从1开始
  • 如果值保持不变或增加,计数变为2及以上
  • 如果值变为0,计数重置为0
  • 如果值再次变为>0,计数又从1开始

日期:

日期    Ref    值    计数
202201 170532 £300.21 1
202202 170532 £600.42 2
202203 170532 £0.00   0
202204 170532 £300.21 1
202205 170532 £600.42 2
202206 170532 £900.63 3

..

尝试了一些我在这里读到的方法,但没有太多帮助。

感谢提供的任何帮助或指导!

英文:

Trying to get a rolling count that resets when 0 is hit.

Only need a few fields.

  • Ordered by the date field and then ref field
  • when value goes 0 to >0 count begins at 1
  • If value remains same or increases count goes to 2 and beyond
  • if value goes to 0 count goes back to 0
  • repeats if value changes to >0 again at 1

Date:

Date   Ref    Value   Count
202201 170532 £300.21 1
202202 170532 £600.42 2
202203 170532 £0.00   0
202204 170532 £300.21 1
202205 170532 £600.42 2
202206 170532 £900.63 3

..
..

Tried a few things i've read on here but not having much joy.

Thanks for any help or direction provided!

答案1

得分: 1

将你的行首先分组,通过计算数据集中之前出现了多少次0,然后你可以在该组上使用ROW_NUMBER。您还需要使用几个CASE表达式来正确放置0。:

WITH Grps AS (
    SELECT Date,
           Ref,
           Value,
           COUNT(CASE Value WHEN 0 THEN 1 END) OVER (ORDER BY Date ASC) AS Grp
    FROM (VALUES (202201, 170532, 300.21),
                 (202202, 170532, 600.42),
                 (202203, 170532, 0.00),
                 (202204, 170532, 300.21),
                 (202205, 170532, 600.42),
                 (202206, 170532, 900.63)) V(Date, Ref, Value)
)
SELECT Date,
       Ref,
       Value,
       CASE Value WHEN 0 THEN 0 ELSE ROW_NUMBER() OVER (PARTITION BY CASE Value WHEN 0 THEN 0 END, Grp ORDER BY Date ASC) END AS RN
FROM Grps
ORDER BY Date ASC;
英文:

Put your rows into groups first, by COUNTing how many times 0 has been in the dataset prior, and then you can use a ROW_NUMBER on that group. You'll need to use couple of CASE expressions as well to put 0 in the right place.:

WITH Grps AS(
    SELECT Date,
           Ref,
           Value,
           COUNT(CASE Value WHEN 0 THEN 1 END) OVER (ORDER BY Date ASC) AS Grp
    FROM (VALUES(202201,170532,300.21),
                (202202,170532,600.42),
                (202203,170532,0.00  ),
                (202204,170532,300.21),
                (202205,170532,600.42),
                (202206,170532,900.63))V(Date,Ref,Value))
SELECT Date,
       Ref,
       Value,
        CASE Value WHEN 0 THEN 0 ELSE ROW_NUMBER() OVER (PARTITION BY CASE Value WHEN 0 THEN 0 END, Grp ORDER BY Date ASC) END AS RN
FROM Grps
ORDER BY Date ASC;

huangapple
  • 本文由 发表于 2023年6月26日 22:05:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557449.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定