简体   繁体   English

MS Access:比较2个表与重复项

[英]MS Access: Compare 2 tables with duplicates

I have two tables which look like this: 我有两个看起来像这样的表:

T1: T1:

ID  |  Date  |  Hour   

T2: T2:

ID  |  Date  |  Hour

I basically need to join these tables when their IDs, dates, and hours match. 当它们的ID,日期和小时数匹配时,我基本上需要加入这些表。 However, I only want to return the results from table 1 that do not match up with the results in table 2. 但是,我只想返回表1中的结果与表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). 我知道这似乎很简单,但我遇到的问题是表1中有多行与表2匹配(任何给定小时都有多个间隔)。 I need to return all of these intervals so long as they do not fall within the same hour period in table 2. 我需要返回所有这些间隔,只要它们不在表2的同一小时内即可。

Example data: 示例数据:

T1: T1:

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

T2: 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. 我的预期结果集是T1的最后2行。 Can anyone point me on the right track?. 谁能指出我在正确的道路上?

I think you just want not exists : 我想你只是想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. 在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: 以下代码返回表1中不同的行,这些行在表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;

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

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