高级查询课堂练习及答案

更新时间:2024-03-31 06:41:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

T-SQL高级查询课堂练习及答案

--练习1

--找出pubs数据库titles表中计算机类图书中价格最高的图书的价格。 USE pubs GO

SELECT max(price) FROM titles where type='popular_comp' GO

--练习2

--查询titles表中有几类图书。 USE pubs GO

SELECT count(distinct type) FROM titles GO

--练习3

--按照州进行分类,查找每个州有几名作者。 USE pubs GO

SELECT state, count(*) FROM authors group by state order by 1 GO

--练习4

--要求按照出版商id进行分类,查找每个出版商的书到目前为止的销售额总和(ytd_sales)。 USE pubs GO

SELECT pub_id, sum(ytd_sales) FROM titles group by pub_id order by 1 GO

--练习5

--在pubs数据库的titles表中,找出平均价格大于18美元的书的种类。 USE pubs GO

SELECT pub_id,avg(price) '平均价格' FROM titles GROUP BY pub_id

HAVING avg(price) > 18

GO

--练习6

--在pubs数据库的titles表中,找出最高价大于20美元的书的种类。 USE pubs GO

SELECT type,max(price) '平均价格' FROM titles GROUP BY type

HAVING max(price) > 20 GO

--练习7 --

找出title_id和pub_name的对应关系。 Use pubs go

Select titles.title_id, publishers.pub_name From titles JOIN publishers

ON titles.pub_id=publishers.pub_id Go

--练习8

--找出title_id, title和pub_name的对应关系。 Use pubs go

Select titles.title_id, titles.title, publishers.pub_name From titles JOIN publishers

ON titles.pub_id=publishers.pub_id Go

--练习9

--查询每个作者的编号,姓名,所出的书的编号,并对结果排序。 Use pubs go

Select authors.au_id,

authors.au_fname + '.' + authors.au_lname 'name', titleauthor.title_id From authors JOIN titleauthor

ON authors.au_id=titleauthor.au_id order by authors.au_id go

10. 从authors表中选择state,city列,从publisher表中选择state,city列,并把两个查询的结果合并为一个结果集,并对结果集按city列、state列进行排序。 use pubs go

select state,city from publishers union

select state,city from authors order by 1,2

11. 对上面的查询语句作修改,保留所有重复的记录。 use pubs go

select state,city from publishers union all

select state,city from authors order by 1,2

12.显示所有来自CA州的作家的全部作品和作家代号。(使用IN,和连接两种方法) use pubs go

select title_id,au_id from titleauthor where au_id in

( select au_id from authors where state = 'CA') order by title_id go

use pubs go

select t.title_id,t.au_id

from titleauthor t join authors a on t.au_id = a.au_id where a.state = 'CA' order by title_id go

13.查找由位于以字母 B 开头的城市中的任一出版商出版的书名:(使用exists和in两种方法)

USE pubs GO

SELECT title FROM titles

WHERE EXISTS (SELECT *

FROM publishers

WHERE pub_id = titles.pub_id AND city LIKE 'B%') GO

USE pubs GO

SELECT title FROM titles

WHERE pub_id IN (SELECT pub_id FROM publishers

WHERE city LIKE 'B%') GO

本文来源:https://www.bwwdw.com/article/9p4r.html

Top