表结构日期 date
用户 userid
其他字段需求:查询把date分组,查出date之前从未出现过的userid个数,即新增用户数如:
date           userid    其他字段
2012-10-01     1
2012-10-01     2
2012-10-01     3
2012-09-22     1
2012-08-22     1
结果为2、3,即一共2个,date、userid皆有索引,查询效率要高,因为数据量很大

解决方案 »

  1.   


    --为什么需要对日期进行分组呢,你不是统计指定日期前未出现过的人数吗?
    with t("date",userid) as(
    select to_date('2012-10-01','yyyy-mm-dd'),1 from dual
    union all select to_date('2012-10-01','yyyy-mm-dd'),2 from dual
    union all select to_date('2012-10-01','yyyy-mm-dd'),3 from dual
    union all select to_date('2012-09-22','yyyy-mm-dd'),1 from dual
    union all select to_date('2012-08-22','yyyy-mm-dd'),1 from dual
    )
    select count(distinct userid) total from t where t."date">trunc(sysdate)
    and not exists(select 1 from t t1 where t.userid=t1.userid and t1."date"<=trunc(sysdate));
      

  2.   

    select Count(*) from tb where date>to_date(date,'yyyy-mm-dd') and userid not in
    (select distinct userid from tb where date<=to_date(date,'yyyy-mm-dd'))
      

  3.   

    还有你的userid,date最好有联合索引,执行效率应会高些
      

  4.   

    with t (dt, userid) as (
    select to_date('2012-10-01', 'yyyy-mm-dd'), 1 from dual
    union all select to_date('2012-10-01', 'yyyy-mm-dd'), 2 from dual
    union all select to_date('2012-10-01', 'yyyy-mm-dd'), 3 from dual
    union all select to_date('2012-09-22', 'yyyy-mm-dd'), 1 from dual
    union all select to_date('2012-08-22', 'yyyy-mm-dd'), 1 from dual
    )
    select distinct(userid) from t where not exists
    (select 1 from t t1 where t.userid=t1.userid and t1.dt < to_date('2012-09-30','yyyy-mm-dd'));把t1.dt < to_date('2012-09-30','yyyy-mm-dd')这里的2012-09-30换成你需要指定的时间。
      

  5.   

    select date,count(distinct t.userid) from stat_log t
    where not exists
      (
      select userid from stat_log
      where userid=t.useridand accessdate<t.accessdate
      )
    group by t.accessdate这样可以吗?再问下,这里的distinct是不是会破换索引啊?
      

  6.   

    distinct应该不会破换索引。
    你查下oracle的执行计划,那是最准确的。