假设数据库 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。
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。
group by substr(workdate,0,6)
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
yujang()老大,你的方法简单管用,但缺点是运行太慢了,我上面的表只是个示例,实际的业务数据有几十万条,运行要很长时间,显示在网页上不现实。
请问还有什么办法?
from temp
group by substr(workdate,1,6)
(select count(distinct name) from table_test s
where substr(s.workdate,1,6)<=substr(a.workdate,1,6)) cnt
from table_test a ;