假如有3个表(A,B,C),每个表有个时间字段
现在要求。A表是 ip量
B表是 pv量
C表是独立访客求选顶时间段内的ip/pv/独立访客量
选定时间要求显示为每天
如果传入 2010-09-27 2010-09-29
结果
ip pv 独立访客 时间
1 3 1 2010-09-27
5 14 7 2010-09-28
3 8 4 2010-09-28我写的sql语句是 先根据传入的时间创建个临时表,表内的数据是从开始时间到结束时间
然后写余下的,但是性能很差。 2个时间如果相差3,5个月,就要耗时6,7秒。
而且我的临时用的是master..spt_values 表的 number列,所以最多只能是2048表记录。
各位看看,我这SQL怎么优化下。create proc PROC_Visitor_Flow
--选定时间内的ip\pv独立访客流量
@starttime datetime, --开始时间
@endtime datetime --结束时间
as
begin
create table #tb(id int identity,t varchar(23))
insert #tb select convert(varchar(10),dateadd(day,number,@starttime),120) from master..spt_values
where type = 'P' and number between 0 and datediff(day,@starttime,@endtime)
select (select count(a.id) from(select count(id) as id from visitor_b
where convert(varchar(10),created,120) = #tb.t group by ipaddress)a) ip,
(select count(id) from tz_page where convert(varchar(10),accesstime,120) = #tb.t) pv,
(select count(id) from visitor_a where convert(varchar(10),accesstime,120) = #tb.t) [in],
t
from #tb
drop table #tb
end
现在要求。A表是 ip量
B表是 pv量
C表是独立访客求选顶时间段内的ip/pv/独立访客量
选定时间要求显示为每天
如果传入 2010-09-27 2010-09-29
结果
ip pv 独立访客 时间
1 3 1 2010-09-27
5 14 7 2010-09-28
3 8 4 2010-09-28我写的sql语句是 先根据传入的时间创建个临时表,表内的数据是从开始时间到结束时间
然后写余下的,但是性能很差。 2个时间如果相差3,5个月,就要耗时6,7秒。
而且我的临时用的是master..spt_values 表的 number列,所以最多只能是2048表记录。
各位看看,我这SQL怎么优化下。create proc PROC_Visitor_Flow
--选定时间内的ip\pv独立访客流量
@starttime datetime, --开始时间
@endtime datetime --结束时间
as
begin
create table #tb(id int identity,t varchar(23))
insert #tb select convert(varchar(10),dateadd(day,number,@starttime),120) from master..spt_values
where type = 'P' and number between 0 and datediff(day,@starttime,@endtime)
select (select count(a.id) from(select count(id) as id from visitor_b
where convert(varchar(10),created,120) = #tb.t group by ipaddress)a) ip,
(select count(id) from tz_page where convert(varchar(10),accesstime,120) = #tb.t) pv,
(select count(id) from visitor_a where convert(varchar(10),accesstime,120) = #tb.t) [in],
t
from #tb
drop table #tb
end
1 3 1 2010-09-27
5 14 7 2010-09-28
3 8 4 2010-09-28 改成 3 8 4 2010-09-28
手误
left join
(
select d=convert(varchar(10),created,120), count(id) as ip
from visitor_b where created>=@starttime and created<@endtime
group by convert(varchar(10),created,120), ipaddress
) b on a.t=b.d
left join
(
select d=convert(varchar(10),accesstime,120), count(id) as pv
from tz_page where accesstime>=@starttime and accesstime<@endtime
group by convert(varchar(10),accesstime,120)
) c on a.t=c.d
left join
(
select d=convert(varchar(10),accesstime,120), count(id) as [in]
from visitor_a where accesstime>=@starttime and accesstime<@endtime
group by convert(varchar(10),accesstime,120)
) d on a.t=d.d
select count(id) from tz_page where convert(varchar(10),accesstime,120) = #tb.t这样的语句写下来,如果用不到索引的话(有聚集的话可以聚集索引扫描),#TB有多少条数据你就要扫描多少次