sql-server – 用前一列更新表,没有任何循环

我有这张桌子

test123                 
rn  pds     pv  bl  ag  pg
1   6817    90  15  1   1
2   6817        12  1   1
3   6817        10  1   2
4   6817        10  1   3
5   6817        11  1   2
1   6818    92  15  1   1
2   6818        12  1   1
3   6818        10  1   2
4   6818        11  1   3
5   6818        9   1   2
6   6818        8   2   1

预期的输出(带有输出循环)将是

test123                 
rn  pds     pv    bl    ag  pg
1   6817    90    15    1   1
2   6817    90    12    1   1
3   6817    180   10    1   2
4   6817    540   10    1   3
5   6817    1080  11    1   2
1   6818    92    15    1   1
2   6818    92    12    1   1
3   6818    184   10    1   2
4   6818    552   11    1   3
5   6818    1104   9    1   2
6   6818    2208   8    2   1

pv可以是(前一行中的pv值)(ag)(pg)的乘积
 请看一下这个link

update b set b.pv=(a.pv*b.ag*b.pg) 
from test123 a 
left outer join test123 b 
on b.pds=a.pds and b.rn=a.rn+1 and a.pds=b.pds;

最佳答案 如果你的意思是没有while循环,可以使用这样的递归CTE:

查询:

with ord as(
    Select rn, pds, pv, bl, ag, pg, n = ROW_NUMBER() over(partition by pds order by rn)
    From @data  
), loop as (
    select pds, n, pv, mx = ag*pg From ord Where n = 1
    Union All
    Select o.pds, o.n, l.pv, mx * ag*pg From loop l
    Inner Join ord o on l.pds = o.pds and l.n+1 = o.n
)
Select o.rn, o.pds, pv = l.pv*l.mx, o.bl, o.ag, o.pg 
From loop l
Inner Join ord o on o.pds = l.pds and o.n = l.n
Order by o.pds, o.n;

ord用于命令你的pds by rn.
循环是递归cte.它与所有以前的产品一起使用ag * pg.

你的数据:

Declare @data table (rn int, pds int, pv int, bl int, ag int, pg int)
Insert into @data(rn, pds, pv, bl, ag, pg) values
    (1, 6817, 90, 15, 1, 1)
    , (2, 6817, null, 12, 1, 1)
    , (3, 6817, null, 10, 1, 2)
    , (4, 6817, null, 10, 1, 3)
    , (5, 6817, null, 11, 1, 2)
    , (1, 6818, 92, 15, 1, 1)
    , (2, 6818, null, 12, 1, 1)
    , (3, 6818, null, 10, 1, 2)
    , (4, 6818, null, 11, 1, 3)
    , (5, 6818, null, 9, 1, 2)
    , (6, 6818, null, 8, 2, 1);

输出:

rn  pds     pv      bl  ag  pg
1   6817    90      15  1   1
2   6817    90      12  1   1
3   6817    180     10  1   2
4   6817    540     10  1   3
5   6817    1080    11  1   2
1   6818    92      15  1   1
2   6818    92      12  1   1
3   6818    184     10  1   2
4   6818    552     11  1   3
5   6818    1104    9   1   2
6   6818    2208    8   2   1
点赞