假设数据库 tmp 如下:
 name      workdate
  a         20060103
  a         20060201
  b         20060301
  c         20060401
  a         20060102
  d         20060201
........
其中workdate为字符型表示的日期,想求sql语句实现如下结果:
 month     count (计数)
 200601     ?
 200602     ?
 200603     ?
.......
就是按月份分组实现计数,但这个计数的要求是:比如200603月份,要计3月份前所有的,包括1、2、3月份,而且name重复的话,只计一次,即a用户不管在1、2、3月份内出现过多少次,count只加1。

解决方案 »

  1.   

    select distinct substr(workdate,1,6) month,count(distinct name) over(partition by substr(workdate,1,6))  from tmp
      

  2.   

    select substr(workdate,1,6) month,count(distinct name) from temp 
    group by substr(workdate,0,6)
      

  3.   

    SQL>create table table_test(
     2   name varchar2(20),
     3   workdate varchar2(20));
     
     SQL> create or replace function func_on_table_test(p_month varchar2) return varchar2 as
      2   v_count number;
      3   begin
      4   select count(distinct name) into v_count from table_test where substr(workdate,1,6)<=p_month
      5   return v_count;
      6   end;
      7  /
     
    SQL>select substr(workdate,1,6)month,func_on_table_test(substr(workdate,1,6)) count
      2 from table_test
      3 group by substr(workdate,1,6);
    结果:   MONTH        COUNT
    ------------ --------
    200601       1
    200602       2
    200603       3
    200604       4
      

  4.   

    duanzilin(寻)老大,你的语句只统计了当月的数量,我要的是指定日期前所有的计数。
    yujang()老大,你的方法简单管用,但缺点是运行太慢了,我上面的表只是个示例,实际的业务数据有几十万条,运行要很长时间,显示在网页上不现实。
    请问还有什么办法?
      

  5.   

    写错了,再试下:select distinct substr(workdate,1,6) month,count(distinct name) over(order by substr(workdate,1,6))  from tmp
      

  6.   

    好久没用了,忘了分析函数中distinct 和 order by 不能一起用了,只好换个写法了SELECT substr(workdate,1,6) month,(SELECT COUNT(DISTINCT name) FROM a t1 WHERE substr(t1.workdate,1,6) <= substr(t.workdate,1,6)) COUNT FROM a t GROUP BY substr(workdate,1,6)
      

  7.   

    SELECT substr(workdate,1,6) month count(name) 
    from temp
    group by substr(workdate,1,6)
      

  8.   

    select distinct substr(a.workdate,1,6) month,
    (select count(distinct name) from table_test s
    where substr(s.workdate,1,6)<=substr(a.workdate,1,6)) cnt
    from table_test a ;