简体   繁体   中英

Oracle SQL COUNT in an EXISTS SELECT

I want to create a query where I get all posts from my table INV where the INNUM exists more than 2 times in table INVS. This is my query right now, but it fails with the typical "missing right parenthesis" error. But when I run the EXISTS Query isolated, it works....

SELECT WO.WONUM, WO.DESCRIPTION, INV.INNUM, INV.STATUSDATE
     FROM INV LEFT OUTER JOIN WO ON INV.WOID = WO.WOID
     WHERE EXISTS (
      SELECT COUNT(*) FROM INVS WHERE INVS.INNUM = INV.INNUM and INVS.SITEID='ARZ' GROUP BY INVS.INNUM
      HAVING COUNT(*) > 2 ORDER BY INVS.INNUM
     );

I dont really know why!?

Hmmm . . . use a scalar subquery to calculate the count and compare to "2" in the outer query:

SELECT WO.WONUM, WO.DESCRIPTION, INV.INNUM, INV.STATUSDATE
FROM INV LEFT OUTER JOIN
     WO
     ON INV.WOID = WO.WOID
WHERE (SELECT COUNT(*)
       FROM INVS
       WHERE INVS.INNUM = INV.INNUM AND
             INVS.SITEID = 'ARZ' 
      ) > 2;

Your query is relying on a doubly nested correlation clause which Oracle does not support.

You could also move the subquery to the FROM clause, but this version is more in the spirit of how you have written the query.

You get ORA-00907: missing right parenthesis while using the ORDER BY clause in the subquery.

Remove it and you get a valid syntax

Example

with tab as (select rownum id from dual connect by level <= 5
union all
select 3 from dual union all
select 5 from dual)
select * from tab t
where exists
(select count(*) from tab 
 where id = t.id
 group by id
 having count(*) > 1)
;

        ID
----------
         3
         5
         3
         5

This is not a valid syntax --> ORA-00907: missing right parenthesis

select * from tab t
where exists
(select count(*) from tab 
 where id = t.id
 group by id
 having count(*) > 1 order by id)

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