SQL错误:缺少右括号

时间:2014-10-11 06:15:02

标签: sql database oracle

我想将下面的查询用作另一个语句中的子查询,但是当我将它括在括号中时,我得到错误"缺少右括号"。

没有大括号,它的执行情况很好。

这是什么问题?我需要将语句括在大括号中,以将其用作另一个语句的子查询。我该怎么办?

(SELECT dname 
 FROM   student, 
        major 
 WHERE  student.sid = major.sid 
        AND year = 5 
 GROUP  BY year, 
          dname 
 HAVING Count(student.sid) > 5 
 ORDER  BY year) 

2 个答案:

答案 0 :(得分:2)

您不能在ORDER BY内使用IN子查询。因为字面上IN并不关心您指定值的顺序

 with temp as (select dname, count(sid) as majors
 from major 
 group by dname
 order by majors desc)
 select dname
 from temp
 where majors > 15 or dname in  (SELECT dname 
  FROM   student, 
        major 
  WHERE  student.sid = major.sid 
        AND year = 5 
  GROUP  BY year, 
          dname 
  HAVING Count(student.sid) > 5 ) 

答案 1 :(得分:0)

 with   major as (
 select major.dname,major.sid from ( 
                 values ('d1',101), ('d1',102),
                  ('d1',103), ('d2',201), ('d2',202), ('d2',203)
                 ) as major(dname,sid)
),
student as 
(select sid,year from (
values (101,5),(102,5),(103,4),(104,3),(105,2),(106,1),(107,4)
) as student(sid,year)
),
temp as (   
   select major.dname, count(major.sid) as majors
 from     ( 
                 values ('d1',101), ('d1',102),
                  ('d1',103), ('d2',201), ('d2',202), ('d2',203)
                 ) as major(dname,sid)
 group by dname
 --order by majors desc
 --The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
 )
 select dname
 from temp
 where majors > 2 or dname in  (SELECT dname 
  FROM   student, 
        major 
  WHERE  student.sid = major.sid 
        AND year = 5 
  GROUP  BY year, 
          dname 
  HAVING Count(student.sid) > 5 ) 

<强>输出

dname
d1
d2