SQL Server数据查询(基础篇)

建数据库、建表等等基础操作就省略了,看题目的代码就好了。 

-- 1.单表查询
-- (1)选择表中的若干列
-- ①查询所有商店的商店号、商店名。
select shopno,shopname from shop 
-- ②查询所有商品的详细信息。
select x.shopno ,shopname,shopadress,y.prono ,proname,proprice,amount from
shop x ,product y , sale z where x.shopno = z.shopno and y.prono = z.prono 
-- (2)选择表中不重复的元组
-- ①查询销售了商品的商店号。
select distinct shopno from sale where amount is not null
-- (3)选择表中满足条件的元组
-- ①查询销售了p01商品的商店编号。
select shopno from sale where prono = 'p01'
-- ②查询价格在2000~3000的商品号、商品名。
select prono,proname from product where proprice between 2000 and 3000
-- ③查询销售了p01或p02商品的商店号。
select distinct shopno from sale where prono = 'p01' or prono = 'p02'
-- ④查询所有电视商品的品牌、价格。
select proname ,proprice from product where proname like '%电视'
-- ⑤查询销售表中无销售数量的销售记录。
select shopno,prono,amount from sale where amount is null
-- ⑥查询价格在2000元以上的海尔品牌商品。
select prono,proname from product where proprice > 2000 and proname like '%海尔%'
-- (4)使用ORDER BY子句对查询结果进行排序
-- ①查询所有商品的信息,结果按价格降序排列,价格相同时按商品名升序排列。
select * from shop x,product y,sale z where x.shopno = z.shopno and y.prono = z.prono 
order by proprice desc,proname asc
-- (5)使用聚集函数查询
-- ①查询销售了商品p01的商店数以及p01商品的销售总量、平均销售量、最大销售量和最小销售量。
select count(shopno)销售p01的商店数,sum(amount) 销售总量,avg (amount) 平均销售量, max (amount) 
最大销售量,min (amount) 最小销售量 from sale where prono = 'p01'
-- (6)使用GROUP BY子句进行分组查询
-- ①查询各商品的销售总量,只显示销售总量在300以上的商品及销售总量。
select shopno, sum(amount)销售总量 from sale group by shopno having sum(amount) >300 
-- 2.多表查询
-- (1)等值连接查询
-- ①查询每个商店及其销售情况。
select ShopName,Amount from SHOP,SALE where Shop.ShopNo = SALE.ShopNo
-- (2)自然连接查询
-- ①对上例用自然连接完成。
select shop.* , sale.prono,sale.amount from SHOP,SALE where Shop.ShopNo = SALE.ShopNo
-- (3)外连接查询
-- ①查询每个商店及其销售情况,无任何销售记录的商店也要显示其基本信息。
select * from shop left outer join sale on (shop.shopno = sale.shopno)
-- 3.嵌套查询
-- (1)不相关子查询
-- ①查询与红星商店在同一地区的商店信息。
select * from shop  where shopadress = (select shopadress from shop where shopname = '红星'  )
-- (2)相关子查询
-- ①查询至少销售了商店s02所销售的全部商品的商店号。

select  distinct shopno from sale x where not exists
(select * from sale y where y.shopno = 's02' and not exists 
(select * from sale z where x.shopno = z.shopno and y.prono = z.prono  ))


-- 4.使用UNION的集合查询
-- ①查询上海及北京地区的商店信息。
select * from shop where shopadress = '上海'
union 
select * from shop where shopadress = '北京'

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值