[英]SQL query to return column that is associated to another column with a certain value
COL1 ![]() |
COL2 ![]() |
---|---|
10068 ![]() |
CP ![]() |
10068 ![]() |
DF![]() |
10068 ![]() |
DP ![]() |
10069 ![]() |
CP ![]() |
10061 ![]() |
CP ![]() |
I have this table and I am trying to write a SQL query in Oracle, such that it fetches col1s that have corresponding col2 as 'CP' only and nothing else.我有这个表,我正在尝试在 Oracle 中编写一个 SQL 查询,以便它只获取对应 col2 为“CP”的 col1,仅此而已。 In above example, data returned should be 10069 and 10061, it should not return 10068 as it has DF and DP as well associated.
在上面的例子中,返回的数据应该是 10069 和 10061,它不应该返回 10068,因为它有 DF 和 DP 以及关联。
Below is my query but it doesn't work, it is fetching col1 with 10068 as well下面是我的查询,但它不起作用,它也在用 10068 获取 col1
SELECT DISTINCT COL1, COL2
FROM SAMPLETABLE
WHERE COL2 NOT IN ('DF', 'DP')
Can someone help please?有人可以帮忙吗?
You can use group by
and having
:您可以使用
group by
并having
:
select col1
from sampletable t
group by col1
having min(col2) = max(col2) and min(col2) = 'CP'
You can use not exists
你可以使用
not exists
create table SAMPLETABLE ( COL1 int, COL2 varchar(10));
insert into SAMPLETABLE values(10068, 'CP');
insert into SAMPLETABLE values(10068, 'DF');
insert into SAMPLETABLE values(10068, 'DP');
insert into SAMPLETABLE values(10069, 'CP');
insert into SAMPLETABLE values(10061, 'CP');
Query:询问:
select col1,col2 from sampletable a
where not exists
(select 1 from sampletable b where a.col1=b.col1 and b.col2<'CP')
Output: Output:
COL1 ![]() |
COL2 ![]() |
---|---|
10061 ![]() |
CP ![]() |
10069 ![]() |
CP ![]() |
Or you can also use group by with having clause:或者您也可以使用 group by with 子句:
Query:询问:
select col1 from SAMPLETABLE
group by col1
having count(distinct col2)=1
and min(col2) ='CP'
Output: Output:
COL1 ![]() |
---|
10061 ![]() |
10069 ![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.