2015-11-05 40 views
0

是啊对不起,因为贫穷的标题。SQL选择哪里不包括X只有

我用sqlfiddle创建了一个示例数据库,但我很迷茫,我甚至无法开始查询。 http://sqlfiddle.com/#!3/940b7d

在示例数据库中,我需要所有具有设备并且可以拥有设备“CRAPY”的帐号,但前提是它也具有其他任何类型的设备。 因此,在下面的示例中,我将返回12345的值,因为该帐户确实具有设备,即使它也具有“CRAPY” 它也会返回44444和66666,因为它具有设备。 它不会返回67891,因为即使它有设备,它也只有“CRAPY”设备。

上帝,我真希望是明确的,

create table testdb 
(
    Account varchar(5), 
    Equipment varchar(5) 

) 
insert into testdb (Account,Equipment) values ('12345','CDG12') 
insert into testdb (Account,Equipment) values ('12345','CRAPY') 
insert into testdb (Account,Equipment) values ('12345','CDG12') 
insert into testdb (Account,Equipment) values ('12345','CDG12') 
insert into testdb (Account,Equipment) values ('12345','CDG12') 
insert into testdb (Account,Equipment) values ('67891','CRAPY') 
insert into testdb (Account,Equipment) values ('67891','CRAPY') 
insert into testdb (Account,Equipment) values ('67891','CRAPY') 
insert into testdb (Account,Equipment) values ('67891','CRAPY') 
insert into testdb (Account,Equipment) values ('67891','CRAPY') 
insert into testdb (Account,Equipment) values ('44444','YYYYY') 
insert into testdb (Account,Equipment) values ('66666','PPPPP') 
+0

提示:您可以使用'插入TESTDB(客户设备)VALUES( '12345', 'CDG12'),( '12345', 'CRAPY')插入多行。 ..'。 – HABO

回答

-1

如果我们除去“CRAPY”记载,留下的任何账户都需要报(比“CRAPY”等设备)

select distinct account from testdb where Equipment not like 'CRAPY' 

如果你需要看他们有什么设备,或需要的人以DOA快速健全性检查:

select account, Equipment 
from testdb 
where account in 
    (
    select distinct account from testdb where Equipment not like 'CRAPY' 
    ) 
+0

这是最接近我实际已经想出的。 SELECT * FROM TESTDB 其中帐户中 – scripter78

+0

没有理由使用像这里 (从那里设备<>“CRAPY”组按帐户 TESTDB 选择账户) - 你想要一个平等的比赛不是一个模式匹配。此外,你不能拼出不同的。 – cliffordheath

+0

LIKE:作为一名语言学家,当我可以的时候,我更喜欢用单词而不是符号。 DISITINCT:感谢您指出我的错字!修复。 – gadaju

0

使用DISTINCT查询与设备<>“CRAPY”:

SELECT DISTINCT Account FROM testdb 
WHERE Equipment <> 'CRAPY' 

,或者如果你想所有的所有记录的其他领域这样的账户,使用EXISTS:

SELECT * FROM testdb 
WHERE EXISTS(
    SELECT * FROM testdb AS t1 
    WHERE testdb.Account = t1.Account 
     AND t1.Account <> 'CRAPY' 
) 
+0

不知道为什么这得到了投票,答案是正确的。 –

1

这应该是诀窍。

SELECT Account 
FROM testdb 
WHERE Equipment != 'CRAPY' 
GROUP BY Account 

您也可以替换 “<>” 在那里我有 “!=” 如果你喜欢的语法。

编辑:很多其他的答案在这里使用DISTINCT。作为DBA,任何使用DISTINCT的查询都不会通过我的代码审查。这是懒惰的编程,即使它在逻辑上等同于使用GROUP BY。请避免懒惰的DISTINCT查询。

+0

或者如果您使用的是ANSI标准的SQL实现(DB2,MS Access) - 标准没有定义!= – cliffordheath

+1

标记为T-SQL,所以我使用了最清晰的T-SQL语法。 – user5151179

1

我认为你患有一个糟糕的问题陈述。更清晰的声明是返回任何具有非“CRAPY”设备的帐号。 “CRAPY”设备的存在在很大程度上是无关紧要的。

你可以这样做:

SELECT DISTINCT Account FROM testdb WHERE Equipment <> 'CRAPY' 

这将忽略“CRAPY”记录,并只返回与非“CRAPY”设备(不论该帐户是否具有或不具有“CRAPY”设备占 - 我们不在乎)。