Danbo
Danbo

Reputation: 31

how to compare column values from two tables with the same structure then select the column with different value

I have two tables, vessel_details and vessel_history. Both tables have the same fields. I have to compare the values of all the fields and select the column with the different value and not null. For example the field of ship_name, i have to check if the value of the field ship_name from the vessel_details table is different with the ship_name in vessel_history table. If the value is different and not null, i have to select and display the value from the vessel_history.

Any ideas for the right query? thanks.

Upvotes: 0

Views: 632

Answers (1)

schlonzo
schlonzo

Reputation: 1406

SELECT vessel_details.<your_id>, 'Difference in Column ship_name for ship_name = ' + vessel_history.ship_name 
FROM vessel_details
JOIN vessel_history ON vessel_details.<your_id> ON vessel_history.<id_from_vessel_details>
WHERE vessel_details.ship_name <> vessel_history.ship_name

UNION

SELECT vessel_details.<your_id>, 'Difference in Column ship_model for ship_model = ' + vessel_history.ship_model 
FROM vessel_details
JOIN vessel_history ON vessel_details.<your_id> ON vessel_history.<id_from_vessel_details>
WHERE vessel_details.ship_model <> vessel_history.ship_model

.
.
.

And so on for all the columns you want to check.

Ist that what you are looking for?

EDIT for one row per item:

SELECT vessel_details.<your_id>,
CASE WHEN vessel_details.ship_name <> vessel_history.ship_name THEN Convert(bit, 1) ELSE Convert(bit, 0) END AS ship_name_different,
CASE WHEN vessel_details.ship_model <> vessel_history.ship_model THEN Convert(bit, 1) ELSE Convert(bit, 0) END AS ship_model_different
FROM vessel_details
JOIN vessel_history ON vessel_details.<your_id> ON vessel_history.<id_from_vessel_details>
WHERE vessel_details.ship_name <> vessel_history.ship_name 
OR vessel_details.ship_model <> vessel_history.ship_model

Upvotes: 1

Related Questions