第四章 集合运算

该博客通过SQL查询演示了如何在product和product2表中查找售价高于500的商品,计算两表的交集,找出每类商品售价最高的商品及其所在商店,并使用内联结和关联子查询获取此类商品。同时,还展示了如何按价格升序和商品ID排序计算累计售价。
摘要由CSDN通过智能技术生成

练习

4.1找出 product 和 product2 中售价高于 500 的商品的基本信息。

SELECT *
from product
where sale_price > 500
UNION 
SELECT *
from product2
where sale_price >500

4.2借助对称差的实现方式, 求product和product2的交集。

select *
from product 
where product_id not in(
SELECT product_id 
from product 
WHERE product_id  NOT IN (select product_id from product2)
union
select product_id 
from product2 
where product_id  NOT IN (select product_id from product))

4.3每类商品中售价最高的商品都在哪些商店有售 ?

SELECT p.product_id ,product_type ,product_name ,sale_price ,shop_name
from product p 
left outer join shopproduct 
on p.product_id =shopproduct.product_id 
WHERE 1=(select count(DISTINCT sale_price)
          from product p2 
          where p.product_type =p2.product_type 
          and p.sale_price >=p2.sale_price )

4.4分别使用内连结和关联子查询每一类商品中售价最高的商品。

SELECT p.product_id ,p.product_type ,product_name ,sale_price ,shop_name
from product p 
left join shopproduct 
on p.product_id =shopproduct.product_id 
inner join 
(select product_type , max(sale_price) as da
from product p3 
group by product_type )as pda
on p.product_type =pda.product_type 
and p.sale_price =pda.da

4.5用关联子查询实现:在 product 表中,取出 product_id, product_name, sale_price, 并按照商品的售价从低到高进行排序、对售价进行累计求和。

SELECT	product_id, product_name, sale_price
       ,(select SUM(P2.sale_price) 
       		from Product AS P2
       		where ((P1.sale_price > P2.sale_price)
             OR (P1.sale_price = P2.sale_price 
            AND P1.product_id>=P2.product_id)) )       
  FROM Product AS P1 
 ORDER BY sale_price asc, product_id asc ;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值