ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

mysql 练习 exercise 1:逻辑函数 case when expr1 then expr2 [when expr3 then expr4... else expr] end

2021-10-06 23:01:28  阅读:489  来源: 互联网

标签:case ... 01 05 02 when 2020 CC006 CC005




create database exercise;

use exercise;


create table 揽收表(
    运单号 char(7) primary key,
    客户id char(5),
    创建日期 date
);

insert into 揽收表 values
('PNO0001','CC001','2020-05-01'),
('PNO0002','CC002','2020-05-01'),
('PNO0003','CC002','2020-05-02'),
('PNO0004','CC003','2020-05-01'),
('PNO0005','CC003','2020-05-02'),
('PNO0006','CC003','2020-05-03'),
('PNO0007','CC004','2020-05-01'),
('PNO0008','CC004','2020-05-01'),
('PNO0009','CC004','2020-05-02'),
('PNO0010','CC004','2020-05-03'),
('PNO0011','CC004','2020-05-04'),
('PNO0012','CC005','2020-05-01'),
('PNO0013','CC005','2020-05-02'),
('PNO0014','CC005','2020-05-02'),
('PNO0015','CC005','2020-05-03'),
('PNO0016','CC005','2020-05-04'),
('PNO0017','CC005','2020-05-05'),
('PNO0018','CC006','2020-05-03'),
('PNO0019','CC006','2020-05-06'),
('PNO0020','CC006','2020-05-07'),
('PNO0021','CC006','2020-05-08'),
('PNO0022','CC006','2020-05-10'),
('PNO0023','CC006','2020-05-11'),
('PNO0024','CC006','2020-05-12'),
('PNO0025','CC006','2020-05-13'),
('PNO0026','CC006','2020-05-15'),
('PNO0027','CC006','2020-05-18'),
('PNO0028','CC006','2020-05-22'),
('PNO0029','CC006','2020-05-25'),
('PNO0030','CC006','2020-06-10');


#charlly 编写
select 单量,count(客户id) from
(select 客户id,
case when count(distinct 运单号)<=5 then '0-5'
    when count(distinct 运单号)<=10 then '6-10'
    when count(distinct 运单号)<=20 then '11-20'
    else '20以上'
        end as 单量
from 揽收表 
where month(创建日期)=5 
group by 客户id) as t
group by 单量;

-- 1.逻辑函数 case when expr1 then  expr2  [when expr3 then  expr4... else expr] end as 新字段名 2.将整个返回结果()命名一个新表t,作为select中一个表
-- 计算创建日期在0501-0531期间客户的单量分布情况


#老师答案
select 单量,count(客户id) as 客户数
from 
    (select 
        客户id,
        count(distinct 运单号) as 下单次数,
        case when count(distinct 运单号)<=5 then '0-5'
             when count(distinct 运单号)<=10 then '6-10'
             when count(distinct 运单号)<=20 then '11-20'
             else '20以上'
        end as 单量
    from 揽收表
    where month(创建日期)=5
    group by 客户id) as t
group by 单量;

 

 

 

标签:case,...,01,05,02,when,2020,CC006,CC005
来源: https://www.cnblogs.com/charlly/p/15374539.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有