select ... from table where col between 1 and 9
union
select ... from table where col between 10 and 39
union
................

解决方案 »

  1.   

    Oracle  9i 也可用case when
      

  2.   

    看不懂意思?对不起。我再来说一遍,不知道能不能说清楚。简单举例说来,就是有
    table(col1,col2),想把col1分组后计算sum(col2).
    就需要这样写   select  sum(col2)
                   from talbe
                   group by  (col1所在的组) 
    这里不是以col1的值来group化,是把col1的值按照一定的标准分成若干组后计算每一组的sum(col2).用union好像比decode更麻烦。等于先做成了20多个view然后再union.我用的就是9i,不知道还有case when。可以教教我吗?可以在其中用不等比较或者between吗?
      

  3.   

    我刚才试了一下,case when col1  between 1 and 9 then 1
                         when col1  between 10 and 39 the 2 end case
    可以放在select中,但是却不能放在group by 中,这是怎么回事?
      

  4.   

    select sum(col2) from (select col2,(case when col1  between 1 and 9 then 1 when col1  between 10 and 39 the 2 end case) as col1 from yourtab) group by col1;
      

  5.   

    或者写个函数,输入为col1的值,返回其分组号。
      

  6.   

    听起来很不错。怎样做一个在SQL中执行的函数呢?可以教给我吗?效率如何?代替DECODE的话。
      

  7.   

    create or replace function temp(in_value number )
    return varchar2 is
    begin
      if in_value >=1 and in_value <=9 then
         return '0-9';
      elsif in_value <= 39 then
         ...
      else
         return ..
      end if;
    end ;
    /select temp(column1), .... from yourtable;