0

ACCESS 2010 - 我在一个表中有 3 列,并希望选择在第 1 列 (c1) 中重复但在第 2 列 (c2) 和第 3 列 (c3) 中必须是唯一的记录

Table1
   c1          c2          c3
1  bacct1      user1       log1
2  bacct1      user2       log2
3  bacct1      user3       log3
4  bacct2      user4       log4
5  bacct2      user4       log5
6  bacct3      user6       log6
7  bacct3      user7       log6

理想结果:

Query Results
   c1          c2          c3
1  bacct1      user1       log1
2  bacct1      user2       log2
3  bacct1      user3       log3

不应该提取记录 4 到 7,到目前为止,我能够达到理想结果的唯一方法是执行查询 (1),首先找到 c1 的重复项,然后将这些结果分组到另一个查询中 (2),然后重复多次查询 1 和 2,直到我缩小了结果范围,但我希望有一个更优雅的解决方案。

4

1 回答 1

2

表格和数据;你应该自己做这部分。

create table table1 (
  id int primary key, 
  c1 char(6) not null, 
  c2 char(5) not null, 
  c3 char(4) not null
);

insert into table1 values
(1, 'bacct1', 'user1', 'log1'),
(2, 'bacct1', 'user2', 'log2'),
(3, 'bacct1', 'user3', 'log3'),
(4, 'bacct2', 'user4', 'log4'),
(5, 'bacct2', 'user4', 'log5'),
(6, 'bacct3', 'user6', 'log6'),
(7, 'bacct3', 'user7', 'log6');

听起来您正在寻找类似的东西。

select t1.id, t1.c1, t1.c2, t1.c3
from table1 t1
inner join 
    (select c1, count(c1)
     from table1
     group by c1
     having count(c1) > 1) t2
on t1.c1 = t2.c1
inner join 
    (select c2, count(c2)
     from table1
     group by c2
     having count(c2) = 1) t3
on t1.c2 = t3.c2
inner join 
    (select c3, count(c3)
     from table1
     group by c3
     having count(c3) = 1) t4
on t1.c3 = t4.c3

ID   C1      C2     C3
--
1    bacct1  user1  log1
2    bacct1  user2  log2
3    bacct1  user3  log3

阅读您的评论后,这可能更接近您的需要。我用标准 SQL 写了这个。对于 Access,您需要删除注释并为内部 SELECT 语句添加括号。

select t1.id, t1.c1, t1.c2, t1.c3
from table1 t1
inner join 
    (-- Duplicated values in c1
     select c1, count(*)
     from table1
     group by c1
     having count(*) > 1 ) t2
on t1.c1 = t2.c1
inner join 
    (-- Unique combinations of c1 and c2
     select c1, c2, count(*)
     from table1
     group by c1, c2
     having count(c2) = 1 ) t3
on t1.c1 = t3.c1 and t1.c2 = t3.c2
inner join 
    (-- Unique combinations of c1 and c3
     select c1, c3, count(*)
     from table1
     group by c1, c3
     having count(*) = 1 ) t4
on t1.c1 = t4.c1 and t1.c3 = t4.c3
于 2013-07-26T18:08:33.710 回答