1

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

所以首先我需要检查是否有一行有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       |
    +----+--------+--------------+
4

3 回答 3

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'
                 )

我相信第一个使用连接可能会表现最好。

于 2012-08-10T09:18:40.953 回答
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
于 2012-08-10T08:33:34.500 回答
0
SELECT country  FROM table
WHERE status IN ('treated', 'untreated')
GROUP BY country HAVING count(DISTINCT status)=2;

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

于 2012-08-10T08:35:23.347 回答