Task03:复杂一点的查询

学习内容

学习内容

练习题

练习题-第一部分

3.1
创建出满足下述三个条件的视图(视图名称为 ViewPractice5_1)。使用 product(商品)表作为参照表,假设表中包含初始状态的 8 行数据。

条件 1:销售单价大于等于 1000 日元。
条件 2:登记日期是 2009 年 9 月 20 日。
条件 3:包含商品名称、销售单价和登记日期三列。
对该视图执行 SELECT 语句的结果如下所示。
在这里插入图片描述

create view ViewPractice5_1 as 
select product_name, sale_price, regist_date
from product where sale_price >= 1000 and regist_date = "2009-09-20";

3.2
向习题一中创建的视图 ViewPractice5_1 中插入如下数据,会得到什么样的结果呢?

INSERT INTO ViewPractice5_1 VALUES (' 刀子 ', 300, '2009-11-02');

对原表没有影响。
注意:使用INSERT语句进行插入操作的视图必须能够在基表(组成视图查询的表)中插入数据,否则会操作失败。当我们给数据基本表插入新数据时,视图也会同步插入数据。

3.3
请根据如下结果编写 SELECT 语句,其中 sale_price_all 列为全部商品的平均销售单价。
在这里插入图片描述

select product_id, product_name, product_type, sale_price, 
(select avg(sale_price) from product) as sale_price_all
from product;

3.4
请根据习题一中的条件编写一条 SQL 语句,创建一幅包含如下数据的视图(名称为AvgPriceByType)。
在这里插入图片描述

create view AvgPriceByType as 
select p1.product_id, p1.product_name, p1.product_type, p1.sale_price, p2.avg_sale_price
from product as p1, 
	(select product_type,  avg(sale_price) as avg_sale_price from product
    group by product_type) as p2
where p1.product_type = p2.product_type;

练习题-第二部分

3.5
运算或者函数中含有 NULL 时,结果全都会变为NULL ?(判断题)

是的,因此需要使用coalesce函数

3.6
对本章中使用的 product(商品)表执行如下 2 条 SELECT 语句,能够得到什么样的结果呢?
在这里插入图片描述
1:
在这里插入图片描述
2:
在这里插入图片描述

这是因为所有的值都不等于null,任何值in or not in (null)均为空值,要判断是否为null需要用is null 或者是is not null或isnull()函数等

3.7
按照销售单价( sale_price)对练习 6.1 中的 product(商品)表中的商品进行如下分类。

低档商品:销售单价在1000日元以下(T恤衫、办公用品、叉子、擦菜板、 圆珠笔)
中档商品:销售单价在1001日元以上3000日元以下(菜刀)
高档商品:销售单价在3001日元以上(运动T恤、高压锅)
请编写出统计上述商品种类中所包含的商品数量的 SELECT 语句,结果如下所示。

执行结果
在这里插入图片描述

select 
sum(case when sale_price <= 1000 then 1 else 0 end) as low_price,
sum(case when sale_price between 1001 and 3000 then 1 else 0 end) as mid_price,
sum(case when sale_price  >3000 then 1 else 0 end) as high_price
from product;

猜你喜欢

转载自blog.csdn.net/weixin_44424296/article/details/111356915