转载至:https://blog.csdn.net/wqshappy/article/details/6460876
一.针对SQL上机作业(1)第一题定义的三个表(book,card,borrow),用SQL语句实现如下查询:(注:藏书量=库存量+借出数) 1. 求藏书种数、总册数、最高价、最低价。
SELECT COUNT(DISTINCT category)
藏书种数,SUM(total)
总册数,MAX(price)
最高价,MIN(price)
最低价 FROM book;
2. 列出藏书在十本以上的书(书名、作者、出版社、年份)。
SELECT title, author, press,year
FROM book
WHERE total>10;
3. 哪些出版社的总藏书超过100种。
SELECT press
FROM book GROUP BY press HAVING SUM(total)>100;
4. 目前已借出多少册书?
SELECT SUM (total- stock)
FROM book;
5. 年份最久远的书。
SELECT *
FROM book
WHERE year<=(select min(year) from book);
6. “数据库系统原理教程,王珊编,清华大学出版社,1998年出版”还有几本?
select stock数据库系统原理教程还剩的本数
from book where title like '数据库系统原理教程';
7. 哪一年的图书最多?
select year from book group by year having sum(total)>=all(select sum(total)
from book group by year);
还有一个办法,排序后只显示一条结果;在SQlsever2000中
Select top 1 year, sum(total) total_temp
from book group by year order by total_temp;
8. 平均每本借书证的借书册数。
select count(bno)/count(distinct cno) 平均册数
from borrow
9. 今年未借过书的借书证。
Select cno as 今年未借过书的借书证
From card Where not exists (select * from borrow where borrow.cno=card.cno );
10. 哪个系的同学平均借书最多?
SELECT department FROM card,borrow GROUP BY department HAVING count(bno)/count (distinct borrow.cno)>= all(SELECT count(bno)/count(distinct borrow.cno)
FROM borrow,card GROUP BY department)
11. 最近两年都未被借过的书。
select title as 最近两年未借过的书
from book where bno not in (select bno from borrow where borrow between'2008' and '2010')
12. 今年那种书出借最多?
select category 今年借出最多类型的书, (sum(total)-sum(stock)) as 借出总量
from book group by category having (sum(total)-sum(stock))>=all(select (sum(total)-sum(stock)) from book group by category)