Mysql对字段进行分段统计

  1. 云栖社区>
  2. 博客>
  3. 正文

Mysql对字段进行分段统计

记事本 2018-01-23 23:22:35 浏览887
展开阅读全文
最近做手机银行营销名单时,需对评分(pf)和开户率(khl)进行二维统计
评分和开户率需进行分段统计。
其中,评分取值范围:[0,100],开户率取值范围:[0,1]

以下为测试数据:

--测试数据
--检查表是否存在,若存在则删除
DROP TABLE IF EXISTS yingxiao;
--创建测试表:yingxiao
CREATE TABLE yingxiao
            (name varchar(10) NOT NULL ,
             pf double(10,2) NOT NULL,
             khl double(10,2) NOT NULL,
             PRIMARY KEY (name)
             );

--插入测试数据                       
INSERT INTO yingxiao VALUES('a','15','0.15');
INSERT INTO yingxiao VALUES('b','25','0.25');
INSERT INTO yingxiao VALUES('c','35','0.35');
INSERT INTO yingxiao VALUES('d','40','0.4');
INSERT INTO yingxiao VALUES('e','45','0.45');
INSERT INTO yingxiao VALUES('f','55','0.55');
INSERT INTO yingxiao VALUES('g','65','0.65');
INSERT INTO yingxiao VALUES('h','54','0.66');
INSERT INTO yingxiao VALUES('i','75','0.75');
INSERT INTO yingxiao VALUES('j','85','0.85');
INSERT INTO yingxiao VALUES('k','95','0.95');

一、1个字段分段统计
1、方法一:ceil函数
函数名: ceil
用    法:double ceil(double x);
功   能:返回大于或者等于指定表达式的最小整数
说  明:float ceil ( float value )返回不小于 value 的下一个整数,value 如果有小数部分则进一位。ceil() 返回的类型仍然是 float,因为 float 值的范围通常比 integer 要大。
百度关于ceil函数的介绍:https://baike.baidu.com/item/ceil/10931457

select (ceil(pf/20)-1)*20 as min,
       ceil(pf/20)*20 as max,
       count(*)
       from yingxiao group by ceil(pf/20);
6acea5ecf4711a4315d99a3b5fb33d00b2e764d6
评分字段分段统计结果:
[0,20]:1
(20,40]:3
(40,60]:3
(60,80]:2
(80,100]:2

实际上,在统计分组中习惯规定:“上组限不在内”,即:a≤x<b。

2、方法二:case语句
结构:case  when… then …end

SELECT
sum(CASE when pf<20 then 1 else 0 end)   AS '[0,20)',
sum(CASE when  pf>20 and  pf<=40 then 1 else 0 end)  AS '[20,40)',
sum(CASE when  pf>40 and  pf<=60 then 1 else 0 end)  AS '[40,60)',
sum(CASE when  pf>60 and  pf<=80 then 1 else 0 end)  AS '[60,80)',
sum(CASE when  pf>80  then 1 else 0 end)   AS '[80,100]'
FROM yingxiao;
137e5d69a1dbfa90340a4d13dc670af32842c1f9

二、两个字段分段统计
对评分和开户率两个字段进行分组统计,形成二维交叉表,可将上面方法交叉使用。

select (ceil(khl*100/20)-1)*0.2 as khl_min,
        ceil(khl*100/20)*0.2 as khl_max,
        sum(CASE when pf>=0 and pf<=20 then 1 else 0 end)   AS 'pf[0,20]',
        sum(CASE when  pf>=20 and pf<40 then 1 else 0 end)  AS 'pf[20,40)',
        sum(CASE when  pf>=40 and pf<60 then 1 else 0 end)  AS 'pf[40,60)',
        sum(CASE when  pf>=60 and pf<80 then 1 else 0 end)  AS 'pf[60,80)',
        sum(CASE when  pf>=80 and pf<=100 then 1 else 0 end)   AS 'pf[80,100]',
        count(*)   AS 'pf合计'       
FROM yingxiao group by ceil(khl*100/20);

91c70075c99841ffe42830c277b7590432bab745

原文地址:
数据小雄博客:http://www.zhangzhengxiong.com/?id=97

网友评论

登录后评论
0/500
评论
记事本
+ 关注