How to write SQL query to pick one record from two table which are having different column values in SQL Server

vkc1a9a2  于 2023-06-21  发布在  SQL Server
关注(0)|答案(2)|浏览(155)

I have following 2 tables TableA and TableB need to find the difference and get the result from TableA if there is any changes in any of the Cost columns. Ignore the same records from TableA and TableB I have tried with EXCEPT which is yielding the wrong result.

TABLEA
| JobNo | Brand | Cost1 | Cost2 | Cost3 | Cost4 | Cost5 |
| ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
| 175196 | Vintage | 216347 | 217429 | 218516 | 219609 | 220707 |
| 200330 | Vintage | 427169 | 429305 | 431451 | 433608 | 435776 |
| 211746 | Modern | 285621 | 287049 | 288484 | 289927 | 291376 |

TABLEB

JobNoBrandCost1Cost2Cost3Cost4Cost5
175196Vintage227030228165229306230453231605
200330Vintage444551446774449007451252453509
211746Modern285621287049288484289927291376

Result Expected

JobNoBrandCost1Cost2Cost3Cost4Cost5
175196Vintage216347217429218516219609220707
200330Vintage427169429305431451433608435776
SELECT JobNo,Brand,Cost1,Cost2,Cost3,Cost4,Cost5 FROM TableA(NOLOCK)
EXCEPT
SELECT JobNo,Brand,Cost1,Cost2,Cost3,Cost4,Cost5 FROM TableB(NOLOCK)
enyaitl3

enyaitl31#

find the differences between TableA and TableB based on the Cost columns and retrieve the results from TableA if there are any changes

You can use this:

SELECT JobNo, Brand, Cost1, Cost2, Cost3, Cost4, Cost5
FROM (
  SELECT *
  FROM TableA

  EXCEPT

  SELECT *
  FROM TableB
) AS diff;

kxe2p93d

kxe2p93d2#

The EXCEPT is right, you can see it here:

http://sqlfiddle.com/#!18/f6fc2/2

相关问题