简体   繁体   中英

sql for data validation between two tables

I have two tables (Table1 and Table2) I am comparing. Each table has the same four columns: customerid, channeltreeid, producttreeid and consentstatusid. The customerid is what links each record in the tables, but there are cases where customerid is the same but there are different values in the other column. How can I find all such records (those where customerid is the same but at least one other column differs)?

I am enhancing the answer given by @TheImpaler to output ONLY the rows where there is a difference in one or more of the 3 last columns, as it is so I understand the requirements.

select
    t1.customerid,
    t1.channeltreeid, t1.producttreeid, t1.consentstatusid,
    t2.channeltreeid, t2.producttreeid, t2.consentstatusid,
from table1 t1
join table2 t2 on t1.customerid = t2.customerid
where t1.channeltreeid <> t2.channeltreeid
or t1.producttreeid <> t2.producttreeid
or t1.consentstatusid <> t2.consentstatusid

A simple join will do:

select
    t1.customerid,
    t1.channeltreeid, t1.producttreeid, t1.consentstatusid,
    t2.channeltreeid, t2.producttreeid, t2.consentstatusid,
  from table1 t1
  join table2 t2 on t1.customerid = t2.customerid

In any case, I really think this is a bad database modelling. You should revise and fix the model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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