如何在Oracle中的表中查找特定值?

时间:2018-10-05 06:03:14

标签: sql oracle plsql plsqldeveloper

假设我的表是TEST_123,它具有以下记录:

id |  cid | result
------------------
1  |  C-1 |   TAM
2  |  C-1 |   TAM
3  |  C-2 |   RAM
4  |  C-2 |   TAM
5  |  C-3 |   SAM
6  |  C-3 |   SAM

现在我想要的CID仅具有一种类型的结果,因此答案应该是C-1 AND C-3而不是C-2,因为它具有两种不同类型的结果。需要Oracle查询吗?

5 个答案:

答案 0 :(得分:3)

您只需要了解| | |------| | 0718 | GROUP BY子句。

答案很简单

HAVING

注意分组依据select cid from TEST_123 group by cid having count(distinct result) = 1 中选择不同的键; 具有过滤条件,该条件对于组中的所有记录 (在您的情况下为CID

答案 1 :(得分:1)

使用存在,因为每个组的结果都应该相同,所以有点棘手

 select t1.* from TEST_123 t1 where exists(
             select 1 from TEST_123 t2 where t2.cid=t1.cid
                                      and t2.result=t1.result
                                      group by t2.cid,t2.result
                                      having count(*)=
                                       (select count(*) from TEST_123 t3
                                       where t3.cid=t2.cid)
                                      )

例如

with TEST_123 as
(
select 1 as id , 'c-1' as cid , 'tam' as result from dual
union all
select 2 as id , 'c-1' as cid , 'tam' as result from dual
union all
select 3 as id , 'c-2' as cid , 'tam' as result from dual
union all
select 4 as id , 'c-2' as cid , 'ram' as result from dual

)

select distinct t1.cid from TEST_123 t1 where exists(
                 select 1 from TEST_123 t2 where t2.cid=t1.cid
                                          and t2.result=t1.result
                                          group by t2.cid,t2.result
                                          having count(*)=
                                           (select count(*) from TEST_123 t3
                                           where t3.cid=t2.cid)
                                          )

demo

答案 2 :(得分:1)

根据@zaynul的回答,这是另一种变化:

with TEST_123 as
(
select 1 as id , 'c-1' as cid , 'tam' as result from dual
union all
select 2 as id , 'c-1' as cid , 'tam' as result from dual
union all
select 3 as id , 'c-2' as cid , 'tam' as result from dual
union all
select 4 as id , 'c-2' as cid , 'ram' as result from dual
)
select * from test_123 where cid in (
    select cid from test_123 group by cid having count(distinct result) = 1);

答案 3 :(得分:0)

select t.cid from 
(select cid, count(*) as count from table_1 group by cid, result) t 
group by t.cid 
having count(*)=1;

应该为您工作

答案 4 :(得分:0)

我会使用NOT EXISTS

SELECT t.*
FROM table t
WHERE NOT EXISTS (SELECT 1 FROM table t1 WHERE t1.cid = t.cid AND t1.result <> t.result);