仅在值匹配时识别

时间:2019-07-19 22:04:03

标签: sql oracle

我只需要返回具有匹配值的行,例如Value = A,但是我只需要具有A且没有其他值的行。

T1:

ID   Value    
1     A     
1     B     
1     C     
2     A     
3     A    
3     B    
4     A    
5     B    
5     D    
5     E   
5     F    

所需的输出:

2   
4

我该如何实现? 当我尝试以下操作时,也会返回1&3:

 select ID from T1 where Value ='A' 

3 个答案:

答案 0 :(得分:3)

不存在:

select t.id
from tablename t
where t.value = 'A'
and not exists (
  select 1 from tablename
  where id = t.id and value <> 'A'
)

从您发布的样本数据来看,无需使用:

select distinct t.id

但是如果您发现重复的内容,请使用它。
没有空值的另一种方法:

select id
from tablename
group by id
having sum(case when value <> 'A' then 1 else 0 end) = 0

或者如果您想要ID只有1值='A'的行:

select id
from tablename
group by id
having count(*) = 1 and max(value) = 'A'

答案 1 :(得分:2)

我认为最简单的方法是与having进行聚合:

select id
from tablename
group by id
having min(value) = max(value) and
       min(value) = 'A';

请注意,这会忽略NULL的值,因此它可能同时返回idNULL的{​​{1}}。如果您想避免这种情况:

A

答案 2 :(得分:0)

Oracle设置

CREATE TABLE test_data ( ID, Value ) AS
SELECT 1, 'A' FROM DUAL UNION ALL
SELECT 1, 'B' FROM DUAL UNION ALL
SELECT 1, 'C' FROM DUAL UNION ALL
SELECT 2, 'A' FROM DUAL UNION ALL
SELECT 3, 'A' FROM DUAL UNION ALL
SELECT 3, 'B' FROM DUAL UNION ALL
SELECT 4, 'A' FROM DUAL UNION ALL
SELECT 5, 'B' FROM DUAL UNION ALL
SELECT 5, 'D' FROM DUAL UNION ALL
SELECT 5, 'E' FROM DUAL UNION ALL
SELECT 5, 'F' FROM DUAL

查询

SELECT ID
FROM   test_data
GROUP BY ID
HAVING COUNT( CASE Value WHEN 'A' THEN 1 END ) = 1
AND    COUNT( CASE Value WHEN 'A' THEN NULL ELSE 1 END ) = 0

输出

| ID |
| -: |
|  2 |
|  4 |

db <>提琴here