[英]SQL compare data from two tables then return value from different column if conditions
Situation:情况:
I have 2 tables, tblA, tblB.我有 2 张桌子,tblA,tblB。 tblA contains 9000 products information ==> SKU, UPC tblB contains manufacture 1500 products Info ==> sku, UPC The problem is the UPC on tblA has either: blank, corrupted UPC and good UPC. tblA 包含 9000 个产品信息 ==> SKU、UPC tblB 包含制造商 1500 个产品信息 ==> sku、UPC 问题是 tblA 上的 UPC 有:空白、损坏的 UPC 和良好的 UPC。 How can I:我怎样才能:
I want the good UPC to be updated on tblA instead of just viewing it as query.我希望在 tblA 上更新好的 UPC,而不仅仅是将其视为查询。
Thank you all!谢谢你们!
I created some sample data like this (and let me know if the setup of the sample data is incorrect):我创建了一些这样的示例数据(如果示例数据的设置不正确,请告诉我):
create table tblA
(
sku varchar(25),
upc varchar(25)
)
go
create table tblB
(
sku varchar(25),
upc varchar(25)
)
go
insert into tblA values ('sku1', null)
insert into tblB values ('sku1', 'correct upc #1!')
insert into tblA values ('sku2', 'CORRUPT UPC!')
insert into tblB values ('sku2', 'correct upc #2!')
insert into tblA values ('sku3', 'CORRUPT UPC WITH NO MATCH!')
Then I run these update commands:然后我运行这些更新命令:
First, for your point #1:首先,对于你的观点#1:
update tblA set upc = tblB.upc
from tblA
inner join tblB on tblA.sku = tblB.sku and tblA.upc is null
Then for your point #2:那么对于你的观点#2:
update tblA set upc = isnull(tblB.upc, '')
from tblA
left join tblB on tblA.sku = tblB.sku
where tblA.upc like 'CORRUPT%'
-- you'll need to specify the actual criteria that makes a upc corrupted,
-- and replace the "like 'CORRUPT%'" clause!
Afterward, this query:之后,这个查询:
select * from tblA
Gives you:给你:
--sku upc
--sku1 correct upc #1!
--sku2 correct upc #2!
--sku3 <blank>
Any (uncorrupted) upc in tblA without a corresponding sku in tblB would be left alone. tblA 中的任何(未损坏的)upc 在 tblB 中没有相应的 sku 将被单独留下。 Does that put you on the right track?这会让你走上正轨吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.