简体   繁体   中英

How to use results of an oracle sql query with an in operator?

I would like to create a query using an in operator based on the result of a count( ) query having count( ) = 1. Please see query below.

select count(*), pr.oid
join jrtepiperun pr on pr.oid = it.oid
join xownsparts x on x.oidorigin = pr.oid
having count(*) = 1
group by pr.oid;

This query successfully returns a total of 1589 rows of where count(*) = 1 for each row and pr.oid varies. I now want to create another query based on the pr.oid result as shown below.

select * from jpipelinesystem pl
join xsystemhierarchy x on x.oidorigin = pl.oid
join jrtepiperun pr on pr.oid = x.oiddestination
where pr.oid
in
(
select count(*), pr.oid from
rtrprdb.jrtepiperun pr
join rtrprdb.xownsparts x on x.oidorigin = pr.oid
having count(*) = 1
group by pr.oid
);

However, this returns an error stating that there are too many values. ORA-00913: too many values 00913. 00000 - "too many values" *Cause:
*Action: Error at Line: 20 Column: 1

How can I use the results of pr.oid from the first query for the second query? Note that I need to have two columns since I want a condition where count(*) = 1.

Try below way -

you need to remove count(*) from the select list since you are comparing with one value pr.oid

Another mistake was the having clause will always be after group by clause

select * from jpipelinesystem pl
join xsystemhierarchy x on x.oidorigin = pl.oid
join jrtepiperun pr on pr.oid = x.oiddestination
where pr.oid
in
(
select pr.oid from
rtrprdb.jrtepiperun pr
join rtrprdb.xownsparts x on x.oidorigin = pr.oid
group by pr.oid having count(*) = 1
);

You can use another approach also. Use analytical function as follows:

SELECT * FROM 
( SELECT <required columns>, COUNT(1) OVER(PARTITION BY PR.OID) AS CNT
    FROM JPIPELINESYSTEM PL
         JOIN XSYSTEMHIERARCHY X ON X.OIDORIGIN = PL.OID
         JOIN JRTEPIPERUN PR ON PR.OID = X.OIDDESTINATION
         JOIN RTRPRDB.XOWNSPARTS XPR ON XPR.OIDORIGIN = PR.OID
) where CNT = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM