(一)数据准备
CREATE DATABASE test;
use test;
CREATE table 商品(
id int,
name varchar(255),
商品价格 int,
折扣比例 double,
city varchar(255)
);
insert into 商品 values(1,'牛奶',3,0.95,'内蒙');
insert into 商品 values(2,'面包',4,0.5,'内蒙');
insert into 商品 values(3,'方便面',5,0.75,'内蒙');
insert into 商品 values(4,'饼干',6,0.8,'内蒙');
insert into 商品 values(5,'巧克力',10,0.66,'内蒙');
insert into 商品 values(6,'巧克力',10,0.66,'内蒙');
insert into 商品 values(7,'巧克力',10,0.66,'内蒙');
(二)练习: case关键字
操作背景:对商品进行位置摆放
select name as 姓名,city as 城市,
case
when id is null then '商品编号错误'
when id < 4 then '第一排'
when id >=4 and id <=7 then '第二排'
else '第三排'
end as 位置
from 商品;
数值0的影响:
insert into 商品 values(0,'西瓜',10,0.66,'新疆');
select name as 姓名,city as 城市,
case
when id is null then '商品编号错误'
when id < 4 then '第一排'
when id >=4 and id <=7 then '第二排'
else '第三排'
end as 位置
from 商品;
null值的影响:
insert into 商品 values(null,'面包',10,0.66,'杭州');
select name as 姓名,city as 城市,
case
when id is null then '商品编号错误'
when id < 4 then '第一排'
when id >=4 and id <=7 then '第二排'
else '第三排'
end as 位置
from 商品;
(三)测试
查询商品表中的name,city列,将英文列名替换为中文,对city列字段进行替换:若city为空,替换为'未填写',若city为杭州,替换为'南方',若city为内蒙古,替换为'北方',其他city,替换为'待分类'
select name as 姓名,
case
when city is null then '未填写'
when city = '杭州' then '南方'
when city = '内蒙古' then '北方'
else '待分类'
end as 城市
from 商品;