简体   繁体   English

如何比较具有相同结构的两个表中的列值,然后选择具有不同值的列

[英]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. 我有两个表,vessel_details和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. 我必须比较所有字段的值,并选择具有不同值且不为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. 例如,ship_name字段,我必须检查vessel_details表中的ship_name字段的值是否与vessel_history表中的ship_name不同。 If the value is different and not null, i have to select and display the value from the vessel_history. 如果值不同且不为null,则必须从vessel_history中选择并显示该值。

Any ideas for the right query? 对正确的查询有什么想法吗? thanks. 谢谢。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM