简体   繁体   English

比较并联接多个表,但仅显示是否存在关系

[英]compare and join multiple tables but only show if there is a relation

I have multiple column that i need to compare and join. 我有多个列需要比较和加入。

This is the table i need to use to compare others. 这是我需要用来比较其他人的表格。

MainTable 主表

--Check Number-- --Reimbursement--
-----1000-----------5800.11
-----1001-----------5802.12
-----1002-----------5801.13
-----1003-----------5800.11
-----1004-----------5804.14

Multiple tables like this that I need to compare 我需要比较的多个表格

ChildTable1 子表1

--Check Number --Name----Total Cash---Bonus-
-----1003------John-------5500.11------300
-----1000------Jane-------5502.12------300
-----1002------Joe--------5501.13------300
-----1001------Jay--------5500.11------300
-----1004------Janie------5504.14------300

ChildTable2 子表2

--Check Number --Name----Total Cash---Bonus-
-----1013------John-------5500.11------300
-----1010------Jane-------5502.12------300
-----1002------Joe--------5501.13------300
-----1011------Jay--------5500.11------300
-----1014------Janie------5504.14------300

The End Result should be like this 最终结果应该像这样

--Check Number --Name----Total Cash---Bonus-----Reimbursement--
-----1003------John-------5500.11------300-----------5800.11
-----1000------Jane-------5502.12------300-----------5800.11
-----1002------Joe--------5501.13------300-----------5801.13
-----1001------Jay--------5500.11------300-----------5802.12
-----1004------Janie------5504.14------300-----------5804.14

not

--Check Number --Name----Total Cash1---Bonus1---------Total Cash2---Bonus2-----Reimbursement--
-----1003--------John-------5500.11------300------------------NULL------NULL-----------5800.11
-----1000--------Jane-------5502.12------300------------------NULL------NULL-----------5800.11
-----1002--------Joe--------5501.13------300------------------NULL------NULL-----------5801.13
-----1001--------Jay--------5500.11------300------------------NULL------NULL-----------5802.12
-----1004--------Janie------5504.14------300------------------NULL------NULL-----------5804.14

So I need to compare all tables against the Main table and join only the tables with the same check number 因此,我需要将所有表与主表进行比较,并仅将具有相同校验号的表联接在一起

You can do this as two separate queries and UNION them together: 您可以将其作为两个单独的查询来执行,并将它们联合在一起:

select mt.CheckNumber as CheckNumber,
  c1.name as Name,
  c1.TotalCash as TotalCash,
  c1.Bonus as Bonus,
  mt.Reimbursement as Reimbursement
from MainTable mt
  inner join ChildTable1 c1 on c1.CheckNumber = mt.CheckNumber
UNION
select mt.CheckNumber as CheckNumber,
  c2.name as Name,
  c2.TotalCash as TotalCash,
  c2.Bonus as Bonus,
  mt.Reimbursement as Reimbursement
from MainTable mt
  inner join ChildTable2 c2 on c2.CheckNumber = mt.CheckNumber

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

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