【5.1】用SQL查询请求。(第三章 关系模型中习题用SQL语句编写)
1.出所有顾客、代理商和商品不都在同一个城市,(可能有两个在同一城市)的三元组(cid,aid,pid)
    select distinct cid,aid,pid
    from agents a,customers c,products p
    where a.city<>c.city or c.city<>p.city
2.取出接受顾客c002订单的代理商所在的城市
select city from agents a,orders o
where a.aid=o.aid and cid='c002'
3.取出曾经收到Kyoto的顾客订单的代理商所销售的所有的商品的pid值。 
select distinct pid from orders
    where aid in (select aid from customers c,orders o
    where c.cid=o.cid and cname='Kyoto')
4.出没有通过代理商a03订购过商品的顾客的cid值。 
    select distinct cid from customers
where cid not in(
select cid from orders
where aid='a03')
5.出订购了所有商品的顾客的cid值。
    select c.cid from customers c Where not exists       
(select pid from orders x where not exists         
(select * from orders y Where x.pid=y.pid and y.cid=c.cid))
 
6.取出商品的pname和pid值,要求这些商品所在的城市和某个销售过该商品的代理商所在的城市相同。 
    select p.pname,p.pid from products p,agents a,orders o 
where p.pid=o.pid and a.aid=o.aid and a.city=p.city
7.取出同时订购了商品p01和p07的顾客的pid值。 
    select distinct x.cid from orders x,orders y 
where x.cid=y.cid and x.pid='p01' and y.pid='p07'
8.取出销售过所有曾经被某些顾客订购过的商品的代理商的名字 
    select a.aname from agents a where not exists
(select pid from orders x where not exists
(select * from orders y  Where x.pid=y.pid and y.aid=a.aid))
9.取出所有曾在代理商a03处订购商品的顾客订购过的商品的pid值。
    select distinct pid from orders where cid in
(select cid from orders where aid='a03')
 
10.给出所有的(cname,aname)对,要求对应的顾客曾经在对应的代理商处订购过商品。
    select distinct cname,aname from customers c,agents a,orders o
where c.cid=o.cid and a.aid=o.aid
【5.2】用基本sQL标准来编写能完成下列任务的SQL语句。 
1.如果A是orders表中所有满足cid=x且pid=y的行avg(qty),那我们称顾客x以平均量A订购了select distinct from
一个产品y。可以用一个SQL语句求出以至少300的平均量订购了他们所收到的每样产品的顾客的cid值吗?
select distinct cid from orders group by cid,pid having avg(qty) >=300
2.求出为住在Duluth或Kyoto的所有顾客订购了至少一样公共产品的代理商的aid值。
    select distinct o.aid from orders o,customers c
where (c.city='Duluth' or c.city='Kyoto') and c.cid=o.cid
3.求出被所有住在Dallas的顾客都订购过了的产品的Pid值。
    select distinct p.pid from products p,customers c Where c.city = 'Dallas' and not exists     
(select pid where  not exists
(select * from orders x Where x.pid=p.pid and x.cid=c.cid))
4.在agents表中,删除名为Gray的代理商所在的行,以完整的形式打印出结果表,然后用Insert语句将Gray所在的行放回原表。 
    delete from agents where aname='Gray' 
select * from agents
insert into agents(aid,aname,city,[percent])values('a04','Gray','New York','6')
select * from agents
5.用一个Update语句把存放在Duluth或Dallas的所有产品的价格提高10%。然后重新运行最初用于创建products表并导入数据的过程以恢复表中的原值。 
    update products set price=price*1.1
where city='Duluth' or city='Dallas'
6.写一个SQL查询来求出为住在Duluth的所有顾客订货的代理商的aid和percent值。按照pe
rcent值从大到小的顺序排列结果中的aid值。(注意,如果选择列表中没有包含percent,那就不能根据该列的值来排序。) 
    select a.aid,[percent] from customers c,agents a,orders o 
where c.cid=o.cid and a.aid=o.aid and c.city='Duluth' order by aid desc

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。