如何在 Oracle 的表中查找特定值?
Posted
技术标签:
【中文标题】如何在 Oracle 的表中查找特定值?【英文标题】:How do I find specific values in a table in Oracle? 【发布时间】:2018-10-05 06:03:14 【问题描述】:假设我的表是 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 查询吗?
【问题讨论】:
欢迎来到 Stack Overflow!提问时请更具体一点:到目前为止,您对代码示例进行了哪些尝试? (I downvoted because there is no code) / 您有什么期望? / 您会遇到什么错误? 请查看“How to ask”以获得帮助 【参考方案1】:你只需要了解GROUP BY
和HAVING
子句。
答案很简单
select cid
from TEST_123
group by cid
having count(distinct result) = 1
注意 group by 从CID
中选择不同的键; having 过滤条件适用于组中的所有记录,在您的情况下为count(distinct result) = 1
【讨论】:
谢谢 Marmite .. 虽然它很好地回答了我的查询,但我被 Cid 的 count(result) = 1 卡在了 TEST_123 组中的 select cid 中,并没有区分...但是有一个疑问,当我为 result = TAM 放置 where 子句时,使用这个查询,它给了我 C1 和 C2,但我真正想要的只是 C1,你能理解我吗? 如果您只过滤(使用WHERE
)TAM
- 那么所有剩余的组每个定义只有一个键(TAM
),所以C2
in 结果是可以的。如果您正在寻找只有一种结果类型的键,即TAM
,则必须制定HAVING count(distinct result) = 1 AND max(result) = 'TAM'
(您也可以使用MIN
,因为结果只有一个值.【参考方案2】:
使用存在,它有点棘手,因为每个组的结果应该相同
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
【讨论】:
【参考方案3】:根据@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);
【讨论】:
【参考方案4】:select t.cid from
(select cid, count(*) as count from table_1 group by cid, result) t
group by t.cid
having count(*)=1;
应该适合你
【讨论】:
【参考方案5】:我会使用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);
【讨论】:
以上是关于如何在 Oracle 的表中查找特定值?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Oracle 廉价地验证另一个模式中的表中是不是存在列?
XPath/HtmlAgilityPack:如何查找具有属性 (href) 特定值的元素 (a) 并查找相邻的表列?