查询前50%的数据

实验环境:
create table t (c int);
insert into t values 
(15),(7),(9),(10),(7),(8),(20),(16),(9),(19),
(14),(10),(11),(10),(10),(12),(7),(10),(7),(9);
commit; 


c 等于10,7,9的数量有  11个,超过了半数。
超过半数的 item信息。

通用方式,不依赖具体数据库。


  1. select t5.*,t6.*,ifnull(round(t5.sumtotal/t6.total,2),0) result from (
  2.     select t3.rn,t3.total,t3.c,sum(ifnull(t4.total,0)) sumtotal from (
  3.         select
  4.         t1.*,
  5.         (
  6.             select count(case when t2.total>t1.total then 1 when t2.total=t1.total and t2.c<t1.c then 1 else null end)+1 from (
  7.                 select c,count(*) total from t group by c
  8.             ) t2
  9.         ) rn
  10.         from(
  11.             select c,count(*) total from t group by c order by total desc ,c
  12.         ) t1
  13.     ) t3
  14.     left join(
  15.         select
  16.         t1.*,
  17.         (
  18.             select count(case when t2.total>t1.total then 1 when t2.total=t1.total and t2.c<t1.c then 1 else null end)+1 from (
  19.                 select c,count(*) total from t group by c
  20.             ) t2
  21.         ) rn
  22.         from(
  23.             select c,count(*) total from t group by c order by total desc ,c
  24.         ) t1
  25.     ) t4 on (t3.rn> t4.rn)
  26.     group by t3.rn,t3.total,t3.c
  27. ) t5
  28. left join(
  29.     select count(*) total from t
  30. ) t6 on(1=1)
  31. where ifnull(round(t5.sumtotal/t6.total,2),0)<=0.5;
查询结果:


绑定MySQL的实现

  1. select * from (
  2.     select t3.*,case when result<=0.5 then 1 when result>0.5 and @b=-1 then @b:=1 else null end r from (
  3.         select t1.*,round((@a:=@a+t1.total)/t2.total,2) result from (
  4.             select c,count(*) total from t,(select @a:=0,@b:=-1) vars group by c order by 2 desc
  5.         ) t1
  6.         left join(
  7.             select count(*) total from t
  8.         ) t2 on(1=1)
  9.     ) t3 order by result
  10. ) t4 where r=1;

结果:


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29254281/viewspace-2147318/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29254281/viewspace-2147318/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值