简体   繁体   English

根据其他记录更新记录

[英]Update record based on the other record

I have a table like this, I want to update the value of AttemptNumber column based on record with the value based on the previous record.我有一个这样的表,我想用基于前一条记录的值更新基于记录的AttemptNumber列的值。

txnId交易ID UserId用户身份 Retry重试 AttemptNumber尝试次数
1 1个 12 12 False错误的 0 0
2 2个 12 12 True真的 1 1个
3 3个 12 12 True真的 2 2个
4 4个 12 12 False错误的 0 0
5 5个 12 12 True真的 1 1个
6 6个 12 12 True真的 2 2个
7 7 12 12 False错误的 0 0

Whenever I encounter Retry value as 'False', then I want to keep the AttemptNumber as 0 .每当我遇到Retry值为“False”时,我都想将AttemptNumber保持为0

Whenever I encounter Retry value as 'True', then I want to increment the value in the AttemptNumber .每当我遇到Retry值为“真”时,我都想增加AttemptNumber中的值。 Currently I don't have the column AttemptNumber in the table, I will create the column and update the values based on the value present in 'Retry'.目前我在表中没有 AttemptNumber 列,我将创建该列并根据“重试”中存在的值更新值。

You need to define groups, based on the values in the Retry column and number the rows appropriately:您需要根据Retry列中的值定义组并适当地对行编号:

Test data:测试数据:

SELECT *
INTO Data
FROM (VALUES
   (1, 12, 'False', 0),
   (2, 12, 'True',  0),
   (3, 12, 'True',  0),
   (4, 12, 'False', 0),
   (5, 12, 'True',  0),
   (6, 12, 'True',  0),
   (7, 12, 'False', 0)
) v (TxnId, UserId, Retry, AttemptNumber)

Statement:陈述:

; WITH UpdateCTE AS (
   SELECT 
      TxnId, UserId, Retry, AttemptNumber,
      ROW_NUMBER() 
         OVER (PARTITION BY UserId, GroupId ORDER BY TxnId) - 1 AS NewAttemptNumber
   FROM (
      SELECT 
         *,
         SUM(CASE WHEN Retry = 'False' THEN 1 ELSE 0 END) 
            OVER (PARTITION BY UserId ORDER BY TxnId) AS GroupId
      FROM Data
   ) t  
)
UPDATE UpdateCTE
SET AttemptNumber = NewAttemptNumber

Result:结果:

TxnId交易编号 UserId用户身份 Retry重试 AttemptNumber尝试次数
1 1个 12 12 False错误的 0 0
2 2个 12 12 True真的 1 1个
3 3个 12 12 True真的 2 2个
4 4个 12 12 False错误的 0 0
5 5个 12 12 True真的 1 1个
6 6个 12 12 True真的 2 2个
7 7 12 12 False错误的 0 0

you can use this code你可以使用这个代码

declare @x int=0
update t1 set
[AttemptNumber]=iif(t1.Retry=1,@x,0),
@x=iif(t1.Retry=1,(@x + 1),0)
from t1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM