2013-05-16 134 views
1

想象我有如下表:SQL:選擇具有條件的行?

enter image description here

我搜索是:

select count(id) where "colX is never 20 AND colY is never 31" 

預期結果:

3 (= id numbers 5,7,8) 

而且

select count(id) where "colX contains (at least once) 20 AND colY contains (at least once) 31" 

預期結果:

1 (= id number 2) 

我感謝所有幫助

+0

[你有什麼想法](http://mattgemmell.com)/2008/12/08 /什麼具備的,你試了/)?這是一項家庭作業嗎? – creinig

+0

這不是功課。我在另一個select查詢中嘗試了select語句,但我沒有得到我想要的結果 – Anonymous

回答

4

這是一個「爲例套,內集「子查詢。最好的方法是使用having子句進行聚合,因爲它是最通用的方法。這會產生這樣的id的列表:

select id 
from t 
group by id 
having SUM(case when colX = 20 then 1 else 0 end) = 0 and -- colX is never 20 
     SUM(case when colY = 31 then 1 else 0 end) = 0  -- colY is never 31 

您可以使用子查詢數數:

select count(*) 
from (select id 
     from t 
     group by id 
     having SUM(case when colX = 20 then 1 else 0 end) = 0 and -- colX is never 20 
      SUM(case when colY = 31 then 1 else 0 end) = 0  -- colY is never 31 
    ) s 

對於第二種情況,你會:

select count(*) 
from (select id 
     from t 
     group by id 
     having SUM(case when colX = 20 then 1 else 0 end) > 0 and -- colX has at least one 20 
      SUM(case when colY = 31 then 1 else 0 end) > 0  -- colY has at least one 31 
    ) s 
+0

- 對於第一種情況;第二次改變'= 0'條件爲'> 0'。 –

4

第一招:

select count(distinct id) 
from mytable 
where id not in (select id from mytable where colX = 20 or colY = 31) 

第二個:

select count(distinct id) 
from mytable t1 
join mytable t2 on t1.id = t2.id and t2.coly = 30 
where t1.colx = 20  
+0

我非常接近這個,我不知道「distinct」。所以這兩個版本(你的和戈登)工作正常,我不知道哪一個接受 – Anonymous

+0

@tombom OP要求兩個條件至少一次。 – Bohemian

+0

@匿名選擇最優雅的那個......即我的! :)儘管如此,我的查詢*更優雅,因此更容易閱讀,這使得它們成爲「更好的代碼」。良好編碼最重要的措施之一是易讀性,簡潔和清潔直接導致易讀性。 – Bohemian

0

在這裏你去:

Select COUNT(distinct ID) 
from Test_Table1 A 
WHERE NOT EXISTS (SELECT 1 from Test_Table1 c 
     WHERE c.id = a.id 
     AND colX =20 AND coly= 31) 

Select COUNT(distinct ID) 
from Test_Table1 A 
WHERE EXISTS (SELECT 1 from Test_Table1 c 
     WHERE c.id = a.id 
     AND colX =20 AND coly= 31)