带括号的SQL问题

时间:2013-07-31 13:57:25

标签: sql oracle parentheses

我在处理此查询时遇到错误:

SELECT *
FROM example
WHERE pri IN (
    SELECT pri
    FROM (
        SELECT pri
            ,sbst
            ,st
            ,count(*) AS cnt
        FROM example
        WHERE sbst = 'oi'
        GROUP BY pri
        ) AS tmp
    WHERE cnt = 1
        AND st = 'ko'
    )
AND sbst = 'cp';

错误如下:

  

ORA-00907:缺少右括号   00907. 00000 - “缺少右括号”   *原因:
  *动作:行错误:5列:136

但我不认为我错过了一个括号。

2 个答案:

答案 0 :(得分:5)

可能你需要GROUP BY pri,sbst,st

SELECT * 
from example 
WHERE pri IN 
(
    SELECT pri 
    FROM 
    (
        SELECT  pri, 
                sbst, 
                st, 
                count(*) AS cnt 
        FROM example 
        WHERE sbst = 'oi' 
        GROUP BY pri, 
                 sbst, 
                 st
    ) tmp 
    WHERE cnt = 1 AND st = 'ko'
) AND sbst = 'cp';

答案 1 :(得分:0)

请格式化长查询。然后你可以看到什么是错的。还使用别名来避免隐藏的错误

select *
from example as e
where
   e.pri in (
       select
           tmp.pri
       from (
           select e2.pri, e2.sbst, e2.st, count(*) as cnt
           from example as e2
           where e2.sbst = 'oi'
           group by e2.pri
       ) as tmp where tmp.cnt = 1 and tmp.st = 'ko'
   ) and e.sbst = 'cp';

很抱歉这不是答案,我真的不喜欢在SO或生产代码中阅读未格式化的查询。