如何在数据库表中获取前x%的值

时间:2010-08-13 12:55:52

标签: sql derby

如何在数据库表中获得前x%的值。

例如,我有一个加载到db表中的日志文件。我想丢掉最长的1%的请求,因为它们会扭曲数据。

有任何简单的方法吗?

BTW我正在使用德比数据库。

由于

1 个答案:

答案 0 :(得分:1)

您需要累计或个人百分比吗?我不知道使用Derby计算累计总数的方法,但我知道H2数据库/ MySQL的方法。因此,只有我的示例的第一部分才适用于Derby。对于MySQL,您需要将CAST(... AS INTEGER)替换为CAST(... AS SIGNED INTEGER):

drop table test;
create table test(data int);
create index idx_test_data on test(data desc);
insert into test values(1), (1), (1), (2);
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test select data from test;
insert into test values(100), (200), (800);
select sum(data), count(*) from test;

select data, (data * 100. / (select sum(data) from test)) percent
from test where data * 100. / (select sum(data) from test) < 1 order by data desc;

select @acc := 0, @total := sum(data) from test;
create table pa as select data, cast(@acc := @acc + (data * 100. / @total) as integer) percent_acc
from test order by data desc;
select * from pa where percent_acc > 2 limit 10;
drop table pa;