0

我正在尝试根据初始表和连接表之间的连接来增加 sql server 表上的列。这个想法是更新tblForm10Objectives,将ObjectiveNumber列设置为从 1 开始的增量数,基于从连接返回的行数tblForm10GoalsObjectivestblForm10Objectives其中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
4

1 回答 1

1

您的示例似乎在某处缺少右括号,并且没有要查看的表结构,我无法确定我的答案。看来你有两张桌子:

tblForm10Objectives
-------------------
ID_Form10Objective
ObjectiveNumber
...

tblForm10GoalsObjectives
------------------------
ID_Form10Goal
ID_Form10Objective
...

如果是这种情况,以下查询应为您提供所需的结果:

UPDATE dbo.tblForm10Objectives
SET ObjectiveNumber = rn
FROM dbo.tblForm10Objectives INNER JOIN
(
    SELECT
        ROW_NUMBER() OVER (PARTITION BY OG.ID_Form10Goal
                            ORDER BY O.ID_Form10Objective) AS rn,
        O.ID_Form10Objective
    FROM dbo.tblForm10Objectives O INNER JOIN
        dbo.tblForm10GoalsObjectives OG ON OG.ID_Form10Objective = O.ID_Form10Objective
    Where OG.ID_Form10Goal = 4
) rns ON dbo.tblForm10Objectives.ID_Form10Objective = rns.ID_Form10Objective

如果您运行内部 SELECT 语句,您将看到所需的ObjectiveNumber值以及ID_Form10Objective将使用这些值更新的对应值。

如果您发布您的表格结构,我或其他人可能会提供更多帮助。

于 2013-06-08T00:21:55.013 回答