case.md 1.5 KB
Newer Older
M
union  
Mars Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
# 透视表

Goods 表结构如下

```mysql
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,这个查询应该怎么写?

## 答案

```mysql
select name,
       case 
           when price < 10 then 'cheap'
           when price > 1000 then 'expensive'
           else 'normal'
       end as level
from goods;
```

## 选项

### A

```mysql
select name,
       case price
           when  < 10 then 'cheap'
           when  > 1000 then 'expensive'
           else 'normal'
           end as level
from goods;
```

### B

```mysql
select name,
       case
           when price < 10  'cheap'
           when price > 1000 'expensive'
           else 'normal'
           end as level
from goods;
```

### C

```mysql
select name,
       case
           when price < 10 then 'cheap'
           when price > 1000 then 'expensive'
           case _ 'normal'
           end as level
from goods;
```

### C

```mysql
select name,
       case
           when price < 10 then 'cheap'
           when price > 1000 then 'expensive'
           case _ 'normal'
           end as level
from goods;
```