sqlserver 子查询

--产品id  产品名 单价
select productid,productname,unitprice from products--产品表
--定单编号  产品id  单价  数量
select orderid,productid,unitprice,quantity from [order details]--定单详细表
--定章编号   客户id  货运方式   定单日期
select orderid,customerid,shipname,orderdate from orders--定单表

--1.查找比某一产品贵的产品,并显示产品的所有信息?
--方法1>编程方式
declare @price money
select @price=unitprice from products where productname='Chang'
select  productid,productname,unitprice from products where unitprice>@price
--方法2>一般子查询,主要应用子查询的结果做为其它sql语句的条件
--以下查询,返回一个unitprice列所对应的值
--select unitprice from products where productname='Chang'
select  productid,productname,unitprice from products 
where unitprice>(
select unitprice from products where productname='Chang')

update products set unitprice=unitprice*10
where unitprice>(
select unitprice from products where productname='Chang'
)

--2.查询出销售过50次及以上的产品
--[order details]表中可以得出每件产品销售的次数
--products:表中得到产品信息
--方式1>关连查询
--1.1:关连
select p.productid,p.productname,p.unitprice,o.orderid from products p
inner join [order details] o on p.productid=o.productid
--1.2:分组 count(*):统计符合条件的记录数;分组之后功能为统计组内成员数
select p.productid,p.productname,count(*)
 from products p
inner join [order details] o on p.productid=o.productid
group by p.productid,p.productname
having count(*)>50
--方式2>in子查询
--查询结果单列多行,相当于一个集合
--select productid from [order details] group by productid having count(*)>50
--in 对应集合查询
--select productid,productname,unitprice from products
--where productid in (1,4,5)

select productid,productname,unitprice from products
where productid in (
select productid from [order details] group by productid having count(*)>50
)

--3.查询没有下过定单的客户
--not in子查询
select * from customers 
select customerid from orders group by customerid --已下单的客户
select * from customers where customerid not in
(select customerid from orders group by customerid)

--4.应用:分页查询
declare @pageSize int --每页显示多少条记录
declare @pageNo int --第几页
set @pageSize=5
set @pageNo=2
select top (@pageSize) productid,productname,unitprice from products
where productid not in
(select top ((@pageNo-1)*@pageSize) productid from products)

 

转载于:https://www.cnblogs.com/kite/p/3635579.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值