MySQL过滤一步

时间:2015-12-17 23:02:17

标签: mysql sql

我有一张桌子

create table
(
 col1 int,
 nr   int
);

insert into table (col1, nr) values (1, 1);
insert into table (col1, nr) values (2, 1);
insert into table (col1, nr) values (3, 1);

insert into table (col1, nr) values (10, 2);
insert into table (col1, nr) values (208, 2);

insert into table (col1, nr) values (356, 3);

... 

insert into table (col1, nr) values (43, 10000);
insert into table (col1, nr) values (34, 10000);

根据此示例,max(nr)= 10000.如何使用以下方式过滤上表中数据的查询:

count on (col1) for nr between 1 and 20, the 20 is the step
count on (col1) for nr between 21 and 40
count on (col1) for nr between 41 and 60
...
count on (col1) for nr between X and 10000

这就是我的需要,谢谢:

select 
rownum,
((rownum -1) * 100) + 1 as p_nr_token_start,
rownum * 100 as p_nr_token_end
from (
select 
 @rn:=@rn+1 as rownum
from information_schema.columns a,
(select @rn:=0) b) rr
where (rownum * 100) <= 100000

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

select
  sum(case when nr between 1 and 20 then 1 else 0 end) as step_1_20,
  sum(case when nr between 21 and 40 then 1 else 0 end) as step_21_40,
  sum(case when nr between 41 and 60 then 1 else 0 end) as step_41_60,
  ...
  sum(case when nr between 9981 and 10000 then 1 else 0 end) as step_9981_10000
from table

示例:http://sqlfiddle.com/#!9/343a1/2

您可以使用存储过程创建动态SQL查询并执行它,而不是手动创建。准备动态语句的示例如下:https://irhowto.wordpress.com/2012/10/29/mysql-stored-procedure-prepared-statements-and-sql-injection/

编辑:     分隔符//

create procedure get_data()
begin
    declare max_number int default 10000;
    declare number_counter int default 0;
    set @s = 'select ';
    while number_counter < max_number do
        set @s = concat(@s,
            case when number_counter = 0 then '' else ',' end,
            'sum(case when nr between ', number_counter + 1,
            ' and ', number_counter + 20, ' then 1 else 0 end) '
            ' as step_', number_counter + 1,
            '_', number_counter + 20);
        set number_counter = number_counter + 20;
    end while;
    set @s = concat(@s, ' from test');
    prepare stmt from @s;
    execute stmt;
    deallocate prepare stmt;
end //

delimiter ;

call get_data();

此存储过程将为您提供所需的内容。您将获得500列,这可能是非常不切实际的。