SQL查询
数据库中揽收表字段如下:
运单号 客户id 创建日期
PNO0011 CC001 2020/5/1
计算创建日期在0501-0531期间客户的单量分布情况
最终得出数据如下:
单量 客户数
0-5 1000000
6-10 200000
11-20 50000
20以上 30000
我想着用case when 去解决,但又不知道客户数怎么能按照单量分类出来,求解!
你可以用union连接查询多种情况的结果。
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!说下你用的数据库是什么,版本是多少。
这题的思路可以这样,先用case when 按区间获得4个字段,一行数据,然后再进行行列转换,但你没说你用的什么数据库,我先用oracle举个例子
with t as (
select 'PNO0011' 运单号, 'CC001' 客户id, '2020-05-01' 创建日期 from dual)
select * from (
select
count(case when ct between 0 and 5 then 1 end) t0_t5,
count(case when ct between 6 and 10 then 1 end) t6_t10,
count(case when ct between 11 and 20 then 1 end) t11_t20,
count(case when ct > 20 then 1 end) t20_max from
(select 客户id,count(1) ct from t group by 客户id))
unpivot (v for 单量 in (T0_T5, T6_T10, T11_T20, T20_MAX))
mysql的话,用下面这个写法
with t as (
select 'PNO0011' 运单号, 'CC001' 客户id, '2020-05-01' 创建日期 from dual)
select 单量,客户数 from (
select
count(case when ct between 0 and 5 then 1 end) a,
count(case when ct between 6 and 10 then 1 end) b,
count(case when ct between 11 and 20 then 1 end) c,
count(case when ct > 20 then 1 end) d from
(select 客户id,count(1) ct from t group by 客户id) t1) t2
cross join lateral (
select a, '0-5' union all
select b, '6-10' union all
select c, '11-20' union all
select d, '20以上'
) as x(客户数, 单量)