如何基于两个已连接的表来增加列

时间:2013-06-07 22:34:48

标签: sql sql-server-2008

我正在尝试根据初始表和连接表之间的连接来增加sql server表上的列。我们的想法是更新tblForm10Objectives,根据ObjectiveNumbertblForm10GoalsObjectives tblForm10Objectives的联接返回的行数,将ID_Form10Goal列设置为以1开头的增量编号。 {1}}等于一个数字。到目前为止的示例查询:

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语句:

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

1 个答案:

答案 0 :(得分: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

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