2017-02-21 74 views
1
A B C 
1 bob 55 0 
2 bob 55 1 

我需要幫助我的where子句。上面的例子顯示Bob有兩個記錄。我只想顯示記錄是否所有Bob的記錄在列C中的值都是1。如果Bob的記錄中有一個記錄的值爲0,那麼它應該不會爲Bob返回任何值。目前,我只能夠得到它返回擁有的1SQL哪裏條款幫助需要

現有查詢

select a, b, c 
from table 
where b = 55 and c = 1 
+0

所以 - 「C」列中唯一可能的值是0和1?它可以是'空'嗎?另外,A'或'B'可以'空'嗎?而且:如果你有兩個相同的行,用'bob 55 1',你是否需要返回它們兩個? (也就是說,如果它們存在,保留基表中的重複項?)或者保證輸入中不會有重複項? – mathguy

+0

0和1是C列中唯一可能的值。 – user3007002

回答

1

最簡單的辦法值的一個記錄可能是使用not exists

select t.* 
from t 
where not exists (select 1 
        from t t2 
        where t2.a = t.a and t2.c <> 1 
       ); 
+0

感謝大家的幫助! – user3007002

0

嘗試使用NOT EXISTS如下

select a, b, c 
    from table t 
    where t.b = 55 and not exists (select 1 from table t2 
    where t2.b=t.b and t2.c=0) 
0

您可以創建一個子查詢,查找任何記錄等於1。如果發生這種情況,你不會包含它們。

select a, b, c 
    from table as t 
    where not exists (
     select * 
     from table as t1 
     where t.a = t1.a and IsNull(t1.c, -1) <> 1 
    ) 

這樣,就不會不管什麼品種列C值可能發生的,他們將不得不即使你得到一些空的記錄(萬一你不熟悉你的數據。 )。括號內的子查詢可以自行運行以測試或查看是否需要其他條件。

您可以將此表加入自己並完成類似的操作,但我認爲這個代碼示例顯示了意圖。

1

我建議稍微修改SQL(包含在WHERE子句戈登只具備):

select t.a, t.b, t.c 
from table t 
where t.b = 55 and t.c = 1 and not exists (select 1 
        from t t2 
        where t2.a = t.a and t2.b = t.b and t2.c = 0 
       ); 

馬西米諾的解決方案也適用,假設C列永遠只具有或1值2

+0

「1或0的值」我的意思是,當然。 – datadevelopr