实验三 表的集合查询与统计查询实验
二、实验内容
基于实验一建立的 “图书读者数据库”(Book_Reader_DB)和实验二输入的部分虚拟
数据,在 SQL Server 2000 查询分析器的 Transact-SQL 语句输入区输入 Transact-SQL 语句,
然后点击“查询”菜单中的“执行”菜单项(或用 F5 快捷键),执行输入区的 Transact-SQL
语句。
1、集合查询实验
在“图书读者数据库”(Book_Reader_DB)中,用集合查询的方法完成下列查询任
务:
1 查询计算机类和机械工业出版社出版的图书;
select * from Book where bclass='计算机' and bpress='机械工业出版社'
select * from Book where bclass='计算机' union all select * from
Book where bpress='机械工业出版社'
② 查询清华大学出版社出版的书中与机械工业出版社出版的所有不相同的图书号
与书名;
select bno,bname from Book where bpress='清华大学出版社' and bname
not in (select bname from Book where bpress='机械工业出版社')
③ 查询清华大学出版社出版的书与环境类图书的交集;
select * from Book where bpress='清华大学出版社' and bname in (select
bname from Book where bclass='环境')
④ 查询借阅过清华大学出版社出版的“数据结构” 图书和西安电子工业出版社出
版的“操作系统”图书的读者号的并集;
select rno from Borrow inner join Book on Book.bno=Borrow.bno
where bname='数据结构' and bpress='清华大学出版社'
union select rno from Borrow inner join Book on Book.bno=Borrow.bno
where bname='操作系统' and bpress='西安电子工业出版社'
2、统计查询实验
在“图书读者数据库”(Book_Reader_DB)中,用分组、统计与计算的方法完成下
列查询任务:
1 查找这样的图书类别:要求类别中最高的图书定价不低于全部按类别分组的
图书平均定价的 2 倍;
select bclass from Book
group by bclass
having max(bprice)>=2*avg(bprice)
② 求机械工业出版社出版的各类图书的平均定价,用 Group by 来实现;
select bclass,avg(bprice) as avgbprice from Book
where bpress='机械工业出版社'
group by bclass
③ 列出计算机类图书的书号、名称及价格,最后求出册数和总价格;
select bno,bname,bprice,bnumber,bprice*bnumber as sumPrice from
Book where bclass='计算机'
④ 列出计算机类图书的书号、名称及价格,并求出各出版社这类书的总价格,最
后求出全部册数和总价格;
select bno,bname,bprice,bprice*bnumber as grossPrice from Book
where bclass='计算机'
select bpress,bclass,sum(bnumber*bprice) as totalPrice from
Book
where bclass='计算机'
group by bpress,bclass
select sum(bnumber) as totalNumber,sum(bprice) as totalPrice
from Book where bclass='计算机'
⑤ 查询订购图书最多的出版社及订购图书的数量;
select top 1 bpress,sum(bnumber) as 订书量from Book
group by bpress
order by 订书量 desc
⑥ 查询 2000 年以后购买的图书总册数;
select sum(bnumber) as 总册数 from Book where bBuyDate>'2000-01-01'
⑦ 计算各类图书的总册数;
select bclass,sum(bnumber) as 总册数from Book
group by bclass
⑧ 查询每本图书的平均借阅次数;
select bno,count(rno) as 平均借阅次数from Borrow
group by bno