• 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)
  • 相关阅读:
    Python + unittest + HTMLTestRunnerCN 生成接口自动化测试报告
    python 读写操作CSV文件
    with关键字
    Django常规命令大全
    科技阅读与写作资料
    Topics in Service Computing
    学习总结100515
    【论文收集】PQDT硕博库中的搜索结果service composition
    毕业开题结束感想
    excle操作备忘
  • 原文地址:https://www.cnblogs.com/kite/p/3635579.html
Copyright © 2020-2023  润新知