case.md 1.7 KB
Newer Older
M
union  
Mars Liu 已提交
1 2 3 4
# 透视表

Goods 表结构如下

fix bug  
张志晨 已提交
5
```sql
M
union  
Mars Liu 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19
create table goods(
                      id int primary key auto_increment,
                      category_id int,
                      category varchar(64),
                      name varchar(256),
                      price decimal(12, 4),
                      stock int,
                      upper_time timestamp
)
```

Joe 想要做一个报表,只需要显示商品名和价格分级,其中不足10元的是 cheap, 超过1000的是expensive,其它的是 
normal,这个查询应该怎么写?

M
Mars Liu 已提交
20 21
<hr/>

F
feilong 已提交
22
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill){target="_blank"}。
F
feilong 已提交
23

F
feilong 已提交
24 25
* `show databases;` 列出所有数据库
* `show tables;` 列出所有表
M
Mars Liu 已提交
26

M
union  
Mars Liu 已提交
27 28
## 答案

fix bug  
张志晨 已提交
29
```sql
M
union  
Mars Liu 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42
select name,
       case 
           when price < 10 then 'cheap'
           when price > 1000 then 'expensive'
           else 'normal'
       end as level
from goods;
```

## 选项

### A

fix bug  
张志晨 已提交
43
```sql
M
union  
Mars Liu 已提交
44 45 46 47 48 49 50 51 52 53 54
select name,
       case price
           when  < 10 then 'cheap'
           when  > 1000 then 'expensive'
           else 'normal'
           end as level
from goods;
```

### B

fix bug  
张志晨 已提交
55
```sql
M
union  
Mars Liu 已提交
56 57 58 59 60 61 62 63 64 65 66
select name,
       case
           when price < 10  'cheap'
           when price > 1000 'expensive'
           else 'normal'
           end as level
from goods;
```

### C

fix bug  
张志晨 已提交
67
```sql
M
union  
Mars Liu 已提交
68 69 70 71 72 73 74 75 76 77 78
select name,
       case
           when price < 10 then 'cheap'
           when price > 1000 then 'expensive'
           case _ 'normal'
           end as level
from goods;
```

### C

fix bug  
张志晨 已提交
79
```sql
M
union  
Mars Liu 已提交
80 81 82 83 84 85 86 87
select name,
       case
           when price < 10 then 'cheap'
           when price > 1000 then 'expensive'
           case _ 'normal'
           end as level
from goods;
```