Sql 用相关列更新表的最佳方法是什么?

Sql 用相关列更新表的最佳方法是什么?,sql,sql-server,tsql,Sql,Sql Server,Tsql,我不知道如何解决我的问题,所以我希望你能帮我解决这个问题。因此,我有一个表,例如TableA: Id Code ProductId RelatedId 1 APlus 100 NULL 2 AMinus 100 NULL 3 BPlus 200 NULL 4 BMinus 200 NULL 现在,我有RelatedId=NULL,我想得到这个结果: Id Code ProductId Rel

我不知道如何解决我的问题,所以我希望你能帮我解决这个问题。因此,我有一个表,例如TableA:

Id  Code    ProductId  RelatedId
1   APlus   100        NULL
2   AMinus  100        NULL
3   BPlus   200        NULL
4   BMinus  200        NULL
现在,我有RelatedId=NULL,我想得到这个结果:

Id  Code    ProductId  RelatedId
1   APlus   100        2
2   AMinus  100        1
3   BPlus   200        4
4   BMinus  200        3
对于每个ProductId和代码都是严格连接在一起的,它们的正负代码是相同的

我应该创建一些游标吗?但是我该拿什么呢?身份证

您可以使用外部应用。这里有一种方法:

select t.*, t2.id
from t outer apply
     (select top 1 t2.*
      from t
      where t2.productid = t.productid and
            t2.code <> t.code
     ) t2;
我应该注意,这很容易适应更新:

您可以使用外部应用程序。这里有一种方法:

select t.*, t2.id
from t outer apply
     (select top 1 t2.*
      from t
      where t2.productid = t.productid and
            t2.code <> t.code
     ) t2;
我应该注意,这很容易适应更新:

您可以使用子查询:

您可以使用子查询:

试试这个

update cte set cte.RelatedId  = cte1.Id from CTE 
inner join CTE cte1 on CTE.ProdecTid = cte1.ProdecTid and CTE.Id != cte1.Id
这是您的表名

试试这个

update cte set cte.RelatedId  = cte1.Id from CTE 
inner join CTE cte1 on CTE.ProdecTid = cte1.ProdecTid and CTE.Id != cte1.Id
这是您的表名

update cte set cte.RelatedId  = cte1.Id from CTE 
inner join CTE cte1 on CTE.ProdecTid = cte1.ProdecTid and CTE.Id != cte1.Id