Oracle内等距查询

来源:互联网 发布:域名泛解析 编辑:程序博客网 时间:2024/06/10 14:25

数据表内有列分数字段,分数0~600不等,现在需要统计各个分段内的人数,分段距离为50分计算一次,计算结果类似:

  1. 0~50 100
  2. 50~100 100
  3. 100~150 100
  4. 150~200 100
  5. ****
    方案一:
    一般写法为根据各个分数值进行case when判断是否在该区间内,然后赋值,代码如下:
select xyf,count(1) from (select (case when t.xyf >= 0 and t.xyf < 50 then '0~50' when        t.xyf >= 50 and t.xyf < 100 then '50~100' when        t.xyf >= 100 and t.xyf < 150 then '100~150' when        t.xyf >= 150 and t.xyf < 200 then '150~200' when        t.xyf >= 200 and t.xyf < 250 then '200~250' when        t.xyf >= 250 and t.xyf < 300 then '250~300' when        t.xyf >= 300 and t.xyf < 350 then '300~350' when        t.xyf >= 350 and t.xyf < 400 then '350~400' when        t.xyf >= 400 and t.xyf < 450 then '400~450' when        t.xyf >= 450 and t.xyf < 500 then '450~500' when        t.xyf >= 500 and t.xyf < 550 then '500~550' when        t.xyf >= 550 and t.xyf < 600 then '550~600' else '其他' end) xyf  from t_grxy_xyf t)  group by xyf  order by xyf;

得出结果如下:
方案一
优点:根据需求可以方便的调整统计结果,且简单易写。
缺点:繁琐的复制粘贴。。。

方案二:
根据分值,对当前分段进行取模,如:分数为120分,取模结果为:120/50=2,所属分段为:2*50~2*50+50,即100~150之间,实现代码如下:

select to_char(a * 50) || '~' || to_char(a * 50 + 50) 分段, count(1) 人数  from (select xyf, trunc(xyf / 50, 0) a from T_GRXY_XYF) group by a order by a;

得出结果如下:
方案二

1 0
原创粉丝点击