简体   繁体   English

SQL表达式缺失错误

[英]SQL Expression missing error

I am trying to select from a table with the average of columns from other tables from other tables; 我试图从一个表中选择其他表中其他表的列的平均值; The schema is as follows. 架构如下。

Students ( sid , firstname , l astname , status , gpa , email ) 学生sidfirstname ,l astnamestatusgpaemail

Enrollments ( sid , classid , lgrade ) 报名sidclassidlgrade

Grades ( lgrade , ngrade ) 等级lgradengrade

And the erroneous query is, 而错误的查询是,

select sid, lastname, 
avg( select g.ngrade from grades g, enrollments e 
    where e.sid = sid and g.lgrade = e.lgrade and e.lgrade is not null 
    and g.ngrade is not null) as cgpa
from students
order by cgpa asc;

从子查询中取出分号。

There are several issues: 有几个问题:

  • Remove the semicolon from the subquery. 从子查询中删除分号。
  • You're attempting to use a correlated subquery as a value expression. 您正在尝试将相关子查询用作值表达式。 That's fine, but you have to wrap it in parentheses to do so. 那很好,但是你必须把它包在括号中才能这样做。 I only see one set of parentheses, the ones for the avg() function. 我只看到一组括号,即avg()函数的括号。
  • You're also missing an alias on a column. 您还缺少列上的别名。 For clarity in expressing your intent, you should be consistent and use aliases throughout. 为了清楚地表达您的意图,您应该保持一致并始终使用别名。
  • Last, a GROUP BY clause is required somewhere. 最后,某处需要GROUP BY子句。

All in all, I think the aggregate should be inside the parentheses. 总而言之,我认为聚合应该在括号内。

Try: 尝试:

select
   sid,
   lastname, 
   (
      select avg(g.ngrade)
      from grades g, enrollments e 
      where e.sid = sid and g.lgrade = e.lgrade
      and g.ngrade is not null
   ) as cgpa
from students
order by cgpa asc;

Other notes: e.lgrade is not null is not needed since the condition g.lgrade = e.lgrade already ensures it won't be null. 其他说明: e.lgrade is not null没有必要的,因为条件g.lgrade = e.lgrade已经确保了它不会是空。

Last, I encourage you to learn ANSI join syntax. 最后,我鼓励您学习ANSI连接语法。 You'll thank me later. 你以后会感谢我的。 Seriously, using old-style joins is awful. 说真的,使用旧式连接很糟糕。

select
   s.sid,
   s.lastname, 
   (
      select avg(g.ngrade)
      from
         grades g
         inner join enrollments e
            on g.lgrade = e.lgrade
      where
         g.ngrade is not null
         and s.sid = g.sid
   ) as cgpa
from students s
order by cgpa asc;

In fact, I have a suspicion that simply rewriting the query this way will help expose what's wrong with it--it looks to me like maybe the grades and enrollments tables need another join condition? 事实上,我怀疑只是以这种方式重写查询将有助于揭示它的错误 - 它在我看来可能是gradesenrollments需要另一个连接条件?

Two INNER JOIN s without sub-queries - please try. 两个INNER JOIN没有sub-queries - 请尝试。

SELECT s.sid, s.lastname, avg(g.ngrade) cgpa
FROM Students s
JOIN Enrollments e ON s.sid = e.sid
JOIN Grades g ON e.lgrade=g.lgrade
GROUP BY s.sid, s.lastname
ORDER BY 3;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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