日期:2014-05-16  浏览次数:21185 次

oracle查询新增用户数
表结构

日期 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皆有索引,查询效率要高,因为数据量很大

------解决方案--------------------
SQL code

--为什么需要对日期进行分组呢,你不是统计指定日期前未出现过的人数吗?
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));

------解决方案--------------------
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'))
------解决方案--------------------
还有你的userid,date最好有联合索引,执行效率应会高些
------解决方案--------------------
SQL code
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'));