根据 SQL 中其他列的匹配更新表列

问题描述 投票:0回答:1

我有两个表“table1”和“table2”。如果 table2.EmailId 等于 table2.EmailId,我想用 table2.RespI 更新 table1.PrespI,否则用 table2.RespI(任何 RespI)更新 table1.PrespI,其中 table2.BId 等于 table2.BId 并且 table2.EL 等于 L

表1

EL 唯一ID RespDt RespI PrespI
E cd4fbc4a-a303-42b6-858a-5639525a20e3 2024-03-13 1234567
E dd94ae32-2e22-4969-8e37-6f7711050df7 2024-03-13 6598456
E 570e1a04-b5b8-4a8e-bbc8-588c3157b9a4 2024-03-13 3594685

表2

出价 唯一ID 邮箱地址 RespDt EL RespI
123 cd4fbc4a-a303-42b6-858a-5639525a20e3 [电子邮件受保护] 2024-03-13 E 1234567
123 cd4fbc4a-a303-42b6-858a-5639525a20e3 [电子邮件受保护] 2023-03-13 L 8945632
123 3206a0a4-9859-4a97-92a0-602b527896df [电子邮件受保护] 2023-03-13 L 7798653
541 570e1a04-b5b8-4a8e-bbc8-588c3157b9a4 [电子邮件受保护] 2024-03-13 E 3594685
541 88960021-c6b7-48bf-8421-20fa63296b7d [电子邮件受保护] 2023-03-13 L 4681256
541 0b0fb857-6eb7-4f67-8672-813331b5224e [电子邮件受保护] 2023-03-13 L 0235489
876 dd94ae32-2e22-4969-8e37-6f7711050df7 [电子邮件受保护] 2024-03-13 E 6598456

预计

EL 唯一ID RespDt RespI PrespI
E cd4fbc4a-a303-42b6-858a-5639525a20e3 2024-03-13 1234567 8945632
E dd94ae32-2e22-4969-8e37-6f7711050df7 2024-03-13 6598456
E 570e1a04-b5b8-4a8e-bbc8-588c3157b9a4 2024-03-13 3594685 4681256

我有这个查询,但这只会更新匹配的记录。

UPDATE t1 
    SET t1.PrespI = t3.RespI 
FROM dbo.table1 AS t1 
    INNER JOIN dbo.table2 AS t2 on t1.UniqueId = t2.UniqueId and t2.EL = 'E' 
    INNER JOIN dbo.table2 AS t3 on t2.BId = t3.BId and t3.EL = 'L' 
WHERE t2.EmailId = t3.EmailId;

如果我删除 where 子句 t2.EmailId = t3.EmailId,那么它将始终更新 BId 匹配的任何随机值,但我希望如果电子邮件匹配,则通过电子邮件更新,否则 BId 匹配且 EL 为 L 的任何随机值

sql t-sql join sql-update
1个回答
0
投票

如果将 t2.EL = 'E' 连接条件移至 WHERE 子句中,则可以构造符合您要求的过滤条件。

UPDATE t1 
    SET t1.PrespI = t3.RespI 
FROM dbo.table1 AS t1 
    INNER JOIN dbo.table2 AS t2 on t1.UniqueId = t2.UniqueId 
    INNER JOIN dbo.table2 AS t3 on t2.BId = t3.BId and t3.EL = 'L' 
WHERE (t2.EmailId = t3.EmailId AND  t2.EL = 'E')
     OR 
     (t2.EmailId <> t3.EmailId )

小提琴

EL 唯一ID RespDt RespI PrespI
E cd4fbc4a-a303-42b6-858a-5639525a20e3 2024-03-13 1234567 8945632
E dd94ae32-2e22-4969-8e37-6f7711050df7 2024-03-13 6598456
E 570e1a04-b5b8-4a8e-bbc8-588c3157b9a4 2024-03-13 3594685 4681256
© www.soinside.com 2019 - 2024. All rights reserved.