我需要得到两个表之间的区别。我需要比较两个表中的“产品”,“数量”和“价格”列,并说出它的新记录还是我需要提及更改哪个列值。
示例表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
您可以使用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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句