简体   繁体   中英

MS Access: Compare 2 tables with duplicates

I have two tables which look like this:

T1:

ID  |  Date  |  Hour   

T2:

ID  |  Date  |  Hour

I basically need to join these tables when their IDs, dates, and hours match. However, I only want to return the results from table 1 that do not match up with the results in table 2.

I know this seems simple, but where I'm stuck is the fact that there are multiple rows in table 1 that match up with table 2 (there are multiple intervals for any given hour). I need to return all of these intervals so long as they do not fall within the same hour period in table 2.

Example data:

T1:

 1  |  1/1/2011  |  1
 1  |  1/1/2011  |  1  
 1  |  1/1/2011  |  1   
 1  |  1/1/2011  |  2   

T2:

 1  |  1/1/2011  |  1
 1  |  1/1/2011  |  1

My expected result set for this would be the last 2 rows from T1. Can anyone point me on the right track?.

I think you just want not exists :

select t1.*
from t1
where not exists (select 1
                  from t2
                  where t2.id = t1.id and t2.date = t1.date and t2.hour = t1.hour
                 );

EDIT:

I misread the question. This is very hard to do in MS Access. But, you can come close. The following returns the distinct rows in table 1 that do not have equivalent numbers in table 2:

select t1.id, t1.date, t1.hour, (t1.cnt - t2.cnt)
from (select id, date, hour, count(*) as cnt
      from t1
      group by id, date, hour
     ) t1 left join
     (select id, date, hour, count(*) as cnt
      from t2
      group by id, date, hour
     ) t2 left join
     on t2.id = t1.id and t2.date = t1.date and t2.hour = t1.hour
where t2.cnt < t1.cnt;

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