SQL Server 2008比较同一数据库中的两个表,并更改get列
发布于 2021-05-10 21:23:38
我需要得到两个表之间的区别。我需要比较两个表中的“产品”,“数量”和“价格”列,并说出它的新记录还是我需要提及更改了哪个列值。
示例表A
Product | Qty | Price | Comments
A 20 500 xyz
B 50 200 xyz
C 90 100 abc
示例表B
Product | Qty | Price | Comments
A 20 500 sd
B 70 200 cv
C 90 200 wsd
D 50 500 xyz
目前,我正在使用Expect,它提供了所有新的/不匹配的行。
select Product,Qty,Price
from TableB
except
select Product,Qty,Price
from TableA
Product | Qty | Price
B 70 200
C 90 200
D 50 500
但我需要像下面这样的结果集
Product | Result
B Updated Qty
C Updated Price
D New
关注者
0
被浏览
89
1 个回答
-
您可以使用
LEFT JOIN
:SELECT b.Product, b.Qty, b.Price, Result = CASE WHEN a.product IS NULL THEN 'New' ELSE 'Updated: ' + STUFF( CASE WHEN a.Qty != b.Qty THEN ',Qty' ELSE '' END + CASE WHEN a.Price != b.Price THEN ',Price' ELSE '' END, 1, 1, '') END FROM TableB b LEFT JOIN TableA a ON a.Product = b.Product WHERE a.Product IS NULL OR a.Qty != b.Qty OR a.Price != b.Price;