简体   繁体   English

SQL 更新来自同一个表的数据

[英]SQL UPDATE on with data from same table

I have a next situation with a table, Need to update rows from rows in same table, as you see here:我有一个表的下一个情况,需要从同一个表中的行更新行,如您在此处看到的:

TABLE桌子

ID ID SN序列号 FID FID
1 1 12345 12345 1 1
2 2 1122 1122 2 2
3 3 12345-RG 12345-RG NULL NULL
4 4 1122-RG 1122-RG NULL NULL

I need to UPDATE row 3 from row 1 Column FID(Same SN, different ending only on the end -RG) Update row 4 FROM row 2 Column FID(Same SN, different ending -RG)我需要从第 1 行列 FID 更新第 3 行(相同 SN,仅在末尾不同结尾 -RG)从第 2 行列 FID 更新第 4 行(相同 SN,不同结尾 -RG)

So the result should be:所以结果应该是:

TABLE桌子

ID ID SN序列号 FID FID
1 1 12345 12345 1 1
2 2 1122 1122 2 2
3 3 12345-RG 12345-RG 1 1
4 4 1122-RG 1122-RG 2 2

I have tried many ways but I don't get with this... I tried declaring a temp table and trying to compare from there but still with this issue...我尝试了很多方法,但我没有得到这个......我尝试声明一个临时表并尝试从那里进行比较,但仍然存在这个问题......

Asuming [SN] is being augmented with -RG假设[SN]正在使用-RG进行扩充

Example例子

with cte as (
Select * 
      ,NV = max(FID) over (partition by replace(SN,'-RG','') )
 From YourTable
)
Update cte set FID = NV 
 --Where FID is null  -- Optional

The Updated Table更新的表格

ID  SN          FID
1   12345       1
2   1122        2
3   12345-RG    1
4   1122-RG     2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM