[英]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
) 学生 (
sid
, firstname
,l astname
, status
, gpa
, email
)
Enrollments ( sid
, classid
, lgrade
) 报名 (
sid
, classid
, lgrade
)
Grades ( lgrade
, ngrade
) 等级 (
lgrade
, ngrade
)
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: 有几个问题:
avg()
function. avg()
函数的括号。 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? 事实上,我怀疑只是以这种方式重写查询将有助于揭示它的错误 - 它在我看来可能是
grades
和enrollments
需要另一个连接条件?
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.