我想更新test1
表格的某些行。 ColumnB
必须是10 11,12,13,14 ....
但我的表
例如:
ColumnA是父节点。 ColumnA + ColumnB是主键。例如ColumnA是CustomerNumber。 ColumnB是客户的订单号。
create table test1(ColumnA int, ColumnB int, ColumnC int);
Insert Into test1 Values(1, 9,123);
Insert Into test1 Values(1, 10,0);
Insert Into test1 Values(1, 10,0);
Insert Into test1 Values(1, 10,0);
Insert Into test1 Values(1, 10,0);
Insert Into test1 Values(2, 12,128);
Insert Into test1 Values(2, 12,0);
Insert Into test1 Values(3, 11,145);
Insert Into test1 Values(3, 11,0);
不应该那样:
应该是以下内容:
我的工作代码不正确:
update a set a.ColumnB=a.ColumnB+1
from test1 a
inner join test1 b
on b.ColumnA=a.ColumnA
and a.ColumnC=0;
select * from test1;
我该怎么做?如何将我的第一个表更新为第二个表。
答案 0 :(得分:3)
请尝试:
with T as(
select
row_number() over (partition by ColumnA order by ColumnA) Rnum,
min(ColumnB) over (partition by ColumnA) MinVal,
*
From test1
) update T set ColumnB=MinVal+(Rnum-1)
答案 1 :(得分:1)
试试这个:
WITH CTE
AS
(
SELECT *,
ROW_NUMBER() OVER(PARTITION BY ColumnA
ORDER BY ColumnB) AS RN
FROM test1
)
UPDATE t
SET t.ColumnB = CASE
WHEN RN = 1 THEN ColumnB
ELSE ColumnB + RN - 1
END
FROM CTE AS t;