我正在尝试根据初始表和连接表之间的连接来增加 sql server 表上的列。这个想法是更新tblForm10Objectives
,将ObjectiveNumber
列设置为从 1 开始的增量数,基于从连接返回的行数tblForm10GoalsObjectives
,tblForm10Objectives
其中ID_Form10Goal
等于一个数字。到目前为止的示例查询:
Update tblForm10Objectives
Set ObjectiveNumber = rn
From (
Select ROW_NUMBER() over (PARTITION by OG.ID_Form10Goal) as rn
, *
From (
Select *
From tblForm10GoalsObjectives OG
Join tblForm10Objectives O On OG.ID_Form10Objective = O.ID_Form10Objective
Where OG.ID_Form10Goal = 4
Order by O.ID_Form10Objective
) as tblForm10Objectives;
如果执行查询的选择部分,则会显示列,因此您可以看到ObjectiveNumber
当前为 0 其中ID_Form10Goal
= 4
更新运行后,我需要ObjectiveNumber
显示 1 、 2;因为ID_Form10Goal
= 4 有两行。
我不得不为这个更新语句的逻辑引入一个新表,表名是 tblForm10Goals。目标需要由 ID_Agency 而不是 ID_Form10Goal 拉动我收到一条错误消息,指出“无法绑定多部分标识符 'dbo.tblForm10Objectives.ID_Form10Objective = rns.ID_Form10Objective'。我正在使用以下 SQL 更新语句:
UPDATE dbo.tblForm10Objectives
SET ObjectiveNumber = rn
FROM tblForm10Goals As g
Left Join tblForm10GoalsObjectives gobs ON g.ID_Form10Goal = gobs.ID_Form10Goal
Right Join
(
SELECT
ROW_NUMBER() OVER (PARTITION BY g.ID_Agency
ORDER BY OB.ID_Form10Objective) AS rn,
OB.ID_Form10Objective
FROM tblForm10Goals g
LEFT JOIN dbo.tblForm10GoalsObjectives gobs ON g.ID_Form10Goal = gobs.ID_Form10Goal
RIGHT JOIN dbo.tblForm10Objectives OB ON gobs.ID_Form10Objective = OB.ID_Form10Objective
Where g.ID_Agency = 2
) rns ON dbo.tblForm10Objectives.ID_Form10Object = rns.ID_Form10Objective