如何选择具有多个where条件的行

时间:2017-02-11 04:49:19

标签: sql oracle

不确定标题是否合理。

但这就是我需要的,我在sql上很难:

我有以下数据表

ID| Value
------ | ------
1| A
1| B
1| C
1| D
2| A
2| B
2| C

我需要O / P

2 A
2 B
2 C

使用Select id,其中(A,B,C)中的值为(D)中的值 正在给我o / p

1 A
1 B
1 C
2 A
2 B
2 C

需要选择具有A,B,C而非D的Id。

4 个答案:

答案 0 :(得分:0)

如果您想获得在A,B,C中有一个或多个值的行,而不是D:

select *
from your_table
where value in ('A', 'B', 'C')
    and id not in (
        select id
        from your_table
        where value = 'D'
        );

如果您希望所有三个值A,B,C必须存在于该ID而不是D.

select id,
    value
from (
    select t.*,
        count(distinct value) over (partition by id) n
    from your_table t
    where value in ('A', 'B', 'C')
        and id not in (
            select id
            from your_table
            where value = 'D'
            )
    )
where n = 3;

如果您想获得仅包含A,B,C(并且所有这些都存在)的行,请使用:

select id,
    value
from (
    select t.*,
        count(case 
                when value not in ('A', 'B', 'C')
                    then 1
                end) over (partition by id) n,
        count(distinct case 
                when value in ('A', 'B', 'C')
                    then value
                end) over (partition by id) n2
    from your_table t
    )
where n = 0
    and n2 = 3;

答案 1 :(得分:0)

您可以在HAVING子句中使用条件聚合来筛选每个id的行:

SELECT id
FROM table1
GROUP BY id
HAVING MAX(CASE WHEN value = 'A' THEN 1 ELSE 0 END) = 1
   AND MAX(CASE WHEN value = 'B' THEN 1 ELSE 0 END) = 1
   AND MAX(CASE WHEN value = 'C' THEN 1 ELSE 0 END) = 1
   AND MAX(CASE WHEN value = 'D' THEN 1 ELSE 0 END) = 0

这将显示哪些id值符合您的条件,如果需要,可以将其放在子查询中并将其加入到表中以获取id的所有行:

SELECT a.*
FROM table1 a
JOIN (    SELECT id
          FROM table1
          GROUP BY id
          HAVING MAX(CASE WHEN value = 'A' THEN 1 ELSE 0 END) = 1
             AND MAX(CASE WHEN value = 'B' THEN 1 ELSE 0 END) = 1
             AND MAX(CASE WHEN value = 'C' THEN 1 ELSE 0 END) = 1
             AND MAX(CASE WHEN value = 'D' THEN 1 ELSE 0 END) = 0
    ) b
ON a.id = b.id

答案 2 :(得分:0)

根据您的问题,我了解要查找Value列的计数,其值为A, B, C,但Value不等于D。然后简单地将这3个值放在IN运算符中。我将检索不带D的结果集。

<强>查询

SELECT COUNT(Value) count, Value
FROM your_table_name
WHERE Value in ('A', 'B', 'C')
GROUP BY Value;

答案 3 :(得分:-1)

select id, value 
from my_table
where value in ('A','B','C')
and id = 2