Access 2010 - 在三列中的两列上选择Distinct

时间:2013-07-26 17:23:25

标签: sql ms-access

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几次,直到我缩小了我的结果,但我希望有一个更优雅的解决方案。

1 个答案:

答案 0 :(得分: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语句添加parens。

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