依次向下行,根据另一列中的条件为一列赋值

Successively down the rows, assign value to a column based on conditions in another columns

我想根据 A 列中的值以及 B 列和 C 列之间的比较来填充 New 列。我希望 New 列从一开始就具有初始值 = 1,并保留内存行,但在某些情况下重置为 1。

New设置为1作为初始值。

我们来看第3行:由于A=40>30且B=C,则New=New+1=2,因为上面第2行New=1

让我们看第 6 行:由于 A=40>30 且 B<>C,则 New=1(从头开始计数)。

正在创建初始 table,稍后将在其中操作 New:

CREATE TABLE table_20220112
(
Ordered_by int,
A   float,
B   nvarchar(100) ,
C   nvarchar(100),
New int,
);
INSERT INTO table_20220112
VALUES
(1,10,'Apples','Apples',0),
(2,5,'Apples','Apples',0),
(3,40,'Apples','Apples',0),
(4,10,'Apples','Apples',0),
(5,50,'Apples','Apples',0),
(6,40,'Oranges','Apples',0),
(7,10,'Oranges','Apples',0),
(8,25,'Oranges','Bananas',0);
select * from table_20220112
--drop table table_20220112

代码逻辑是这样的(我不知道对应的SQL语法):

New=1 (initail value before going in a looping down all rows)
If A<=30 Then
   IF B=C Then New=New
   Else if B<>C Then New=1
Else If A>30 Then 
   IF B=C Then New=New+1
   Else if B<>C Then New=1
END IF

期望的结果:

Ordered_by A B C New
1 10 Apples Apples 1
2 5 Apples Apples 1
3 40 Apples Apples 2
4 10 Apples Apples 2
5 50 Apples Apples 3
6 40 Oranges Apples 1
7 10 Oranges Apples 1
8 25 Oranges Bananas 1

使用递归 cte 并使用 CASE 表达式

实现该逻辑
with rcte as
(
    select  Ordered_by, A, B, C, New = 1
    from    #table_20220112
    where   Ordered_by  = 1

    union all

    select  t.Ordered_by, t.A, t.B, t.C, 
            New = case when t.A <= 30 
                       then case when t.B = t.C then r.New else 1 end
                       when t.A >  30 
                       then case when t.B = t.C then r.New + 1 else 1 end
                       end
    from    rcte r
            inner join #table_20220112 t    on  r.Ordered_by    = t.Ordered_by - 1
)
select  *
from    rcte
order by Ordered_by