2 oiu1010110 oiu1010110 于 2016.04.26 12:51 提问

SQL 查询问题 group by

student(sno,sname,,sdept)
course(cno,cname,ccredit)
sc(sno,cno,grade)
为什么这样写不行呢?
//查询CS系成绩最高的学生的学号、姓名以及成绩

select student.sno,sname,grade from student,sc where student.sno = sc .sno
and grade=(select max(grade) from sc where sc.sno = sno and sdept = 'cs')
还有一个问题;
//查询每个系的最高成绩
select sdept,max(grade) from sc,student where sc.sno=student.sno group by sdept;这样写把每个系的最高分列出来了,当我想把sno列出来,所以加上了sc.sno,下面的就什么结果也没有,是错的。
--select sdept,sc.sno,max(grade) from sc,student where sc.sno=student.sno group by sdept,sc.sno
那这样的问题的group by到底该怎么写呢?如果我想把学号等也列出来是不是只可以写成相关查询呢?
select x.sno,sdept,grade from student x,sc where x.sno = sc.sno and grade =
(select max(grade) from sc,student where sc.sno=student.sno and sdept=x.sdept) //这个结果又是对的
谢谢指导。

2个回答

danielinbiti
danielinbiti   Ds   Rxr 2016.04.26 13:37
已采纳
 select student.sno,sname,grade from student,sc where student.sno = sc .sno
and grade=(select max(grade) from sc where sc.sno = sno and sdept = 'cs')
这句不对的原因在于,下面子句中,左边的sdept不存在,在sc表中没有
(select max(grade) from sc where sc.sno = sno and sdept = 'cs')
oiu1010110
oiu1010110 这样写仍然是错的:select x.sno,sname,sc.cno,grade from student x,sc where x.sno = sc.sno and grade=(select max(grade) from sc,student where sc.sno = student.sno and student.sno = x.sno and sdept = 'cs');但是这样是对的:select student.sno,sname,grade from student,sc where student.sno = sc.sno and sdept = 'cs' and grade >=all(select grade from sc,student where student.sno = sc.sno and sdept = 'cs');为什么呢?谢谢
一年多之前 回复
CSDNXIAOS
CSDNXIAOS   2016.04.26 13:02

---所有书籍价格的统计
select sum(price)总价,avg(price)均价,max(price)最高价,min(price)最低价
from titles

---统计where条件的记录
---business类型书籍价格的统计
select sum(price)总价,avg(price)均价,max(price)最高价,min(price)最低价
from tit......
答案就在这里:sql查询 -count,group by,havi..
----------------------Hi,地球人,我是问答机器人小S,上面的内容就是我狂拽酷炫叼炸天的答案,除了赞同,你还有别的选择吗?

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!