SQL - 存在比较

时间:2012-08-10 08:30:44

标签: sql db2 exists

我需要为一个国家/地区选择一个处理行的行,并且同一个国家/地区存在一个未处理的行。对于下表,我将返回id = 1行。

首先,我需要检查是否存在TREATED状态的行,然后我必须检查是否存在UNTREATED状态的行和与{TREATED的行相同的国家/地区1}}状态。

    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       |
    +----+--------+--------------+

3 个答案:

答案 0 :(得分: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'
                 )

我相信第一个使用连接可能会发挥最佳效果。

答案 1 :(得分: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

答案 2 :(得分:0)

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

语法可能因sql而异,不确定db2