淘米水和醋洗头好吗:SQL:怎么样改正这个错误

来源:百度文库 编辑:高校问答 时间:2024/05/01 05:25:02
题目:
列出计算机类图书的书号、名称及价格,最后求出册数和总价格;

虽然题目没有说明册数是总册数,我估计老师的意思是查询总册数

开始的时候是这样写的
select Bno,Bname,Bprice,sum(Bcount)Bcount,sum(Bprice)Bprice
from Book
where Bclass='计算机'
group by Bno
运行当然是错的了,我后来想了一下
书号,名称及价格都是好几行的,
而总册数及总价格都是一行的
所以会出错,但不知道怎么改正,希望有人能够帮助一下,不胜感激

错误不在这里,因为group by Bno,所以Bno外其他的字段都要用sum/max/min等聚合函数包起来,像你这种情况应该这样:

select Bno,Bname,Bprice,Bcount,Bprice,(select sum(Bcount) from Book where Bclass='计算机') as sBcount,(select sum(Bprice) from Book where Bclass='计算机') as sBprice
from Book where Bclass='计算机'

这样得到的记录集中,sBcount和sBprice就是你要的统计值,不过每行都有:)

如果不要求在一次SQL操作中完成,可以用一条语句单独完成这个统计操作。

select sum(Bcount),sum(Bprice) from Book where Bclass='计算机'