2012-08-10 35 views
1

我需要選擇一個國家有一個處理行的行,並且同一個國家存在一個未處理的行。對於下表,我將返回與id = 1行。SQL - 存在比較

所以首先我需要檢查是否有一排TREATED狀態,然後我必須檢查是否有一個UNTREATED狀態的行與TREATED狀態相同的國家。

Table example 1 
    +----+--------+--------------+ 
    | id | country| status  | 
    +----+--------+--------------+ 
    | 1 | SE  | TREATED  | 
    | 2 | DK  | UNTREATED | 
    | 3 | SE  | UNTREATED | 
    +----+--------+--------------+ 

    Result of query 
    +----+--------+--------------+ 
    | id | country| status  | 
    +----+--------+--------------+ 
    | 1 | SE  | TREATED  | 
    +----+--------+--------------+ 

如果不存在未經處理的行或該國不一樣,那麼我們不應該返回任何

Table example 2 
    +----+--------+--------------+ 
    | id | country| status  | 
    +----+--------+--------------+ 
    | 1 | SE  | TREATED  | 
    | 2 | DK  | UNTREATED | 
    | 3 | US  | UNTREATED | 
    +----+--------+--------------+ 

    Result of query (empty) 
    +----+--------+--------------+ 
    | id | country| status  | 
    +----+--------+--------------+ 

回答

2

這裏有一對夫婦的其他選項:

select t1.id,t1.country,t1.status 
    from table t1 
    join table t2 on t1.country=t2.country and t2.status='UNTREATED' 
    where t1.status='TREATED' 


select id,country,status 
      from table t1 
      where 
       t1.status='TREATED' and 
       exists (
         select 1 from table t2 where 
          t2.country = t1.country and 
          t2.status = 'UNTREATED' 
       ) 

我相信第一個,使用一個連接,可能會表現最佳。

+0

我會將您的答案標記爲已接受,因爲這是最容易理解/閱讀的查詢。 – 2012-08-10 10:05:48

0
Select country 
from table 
where status in ('treated', 'untreated') -- only needed if there are other statuses 
group by country 
having count(distinct status) = 2 
+1

um。 'group by'是隱含的嗎? – 2012-08-10 08:36:18

+0

不,好點。編輯 – podiluska 2012-08-10 08:37:40

+0

啊哈,我明白了。不確定。你永遠不知道如何寬鬆你不工作的RDBMS可能會變成;-) – 2012-08-10 08:39:09

0
SELECT country FROM table 
WHERE status IN ('treated', 'untreated') 
GROUP BY country HAVING count(DISTINCT status)=2; 

語法可能會因SQL有所不同,不知道約db2

+0

非常感謝你們。但我想返回身份證,國家和地位(不僅是國家)。 – 2012-08-10 09:00:16

+0

哪個ID?這很多? – 2012-08-10 09:06:54

+0

基本上,你可以調用那些集合(比如'min(id)'),或者你可以用它作爲子查詢。像'SELECT * FROM table WHERE country IN(SELECT *答案中的查詢在這裏*)''。 – 2012-08-10 09:08:24