sql case 的用法

sql case when then else end 用法
    demo1:
    CREATE TABLE `table1` (
    `id`  int(11) NOT NULL ,
    `product`  varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
    `price`  decimal(10,2) NULL DEFAULT NULL ,
    PRIMARY KEY (`id`)
    );
    
    insert into table1 values(1,'香蕉',20.5),(2,'西瓜',15),(3,'杨梅',30),(4,'水果刀',8.5),(5,'铅笔',2),(6,'笔记本',3);
    
    现在有需求,查询文具、水果、日用品的销售价格情况。
        其中香蕉、西瓜、杨梅 是水果
        水果刀为日用品
        铅笔、笔记本是文具
    
    这中情况就可以使用case 将上面信息分组并求其中各类商品的总价值
    
    select 
        case t1.product when '香蕉' then '水果' when '西瓜' then '水果' when '杨梅' then '水果' when '水果刀' then '日用品' when '铅笔' then '文具' when '笔记本' then '文具' else '其他' end as '种类',
        sum(t1.price) as '价格' 
    from table1 t1 
        group by case t1.product when '香蕉' then '水果' when '西瓜' then '水果' when '杨梅' then '水果' when '水果刀' then '日用品' when '铅笔' then '文具' when '笔记本' then '文具' else '其他' end;

case 是一个条件控制语句,但是缺陷是,如果使用了case器sql中要查询的值的范围只在case指定的范围内!

猜你喜欢

转载自blog.csdn.net/qq_37151646/article/details/83098153