客户在购物生命周期里的时间平平均怎么计算,就是相差值相加除以相差值次数
下面是我用EXCEL里做出来的一个值,=sum(相差值)/count(相差值),这个在sql里怎样才能得出最终值26例:
ID 金额 日期 相差值
10017235 115.4 2011年4月21日 0
10017235 99.9 2011年4月21日 28
10017235 279 2011年5月19日 18
10017235 316.9 2011年6月7日 72
10017235 366.9 2011年8月19日 12
10017235 249.6 2011年8月31日 30
10017235 107.1 2011年9月30日
26.66666667
下面是我用EXCEL里做出来的一个值,=sum(相差值)/count(相差值),这个在sql里怎样才能得出最终值26例:
ID 金额 日期 相差值
10017235 115.4 2011年4月21日 0
10017235 99.9 2011年4月21日 28
10017235 279 2011年5月19日 18
10017235 316.9 2011年6月7日 72
10017235 366.9 2011年8月19日 12
10017235 249.6 2011年8月31日 30
10017235 107.1 2011年9月30日
26.66666667
select sum(相差值)*1.0/count(相差值) from tb
go
create table [tb]([ID] int,[金额] numeric(4,1),[日期] varchar(13),[相差值] int)
insert [tb]
select 10017235,115.4,'2011年4月21日',0 union all
select 10017235,99.9,'2011年4月21日',28 union all
select 10017235,279,'2011年5月19日',18 union all
select 10017235,316.9,'2011年6月7日',72 union all
select 10017235,366.9,'2011年8月19日',12 union all
select 10017235,249.6,'2011年8月31日',30 union all
select 10017235,107.1,'2011年9月30日',nullselect sum(相差值)*1.0/count(相差值) from tb
/**---------------------------------------
26.666666666666
警告: 聚合或其他 SET 操作消除了空值。(1 行受影响)
**/
declare @t table([ID] int,[金额] numeric(4,1),[日期] datetime)
insert @t
select 10017235,115.4,'2011-04-21' union all
select 10017235,99.9,'2011-04-21' union all
select 10017235,279,'2011-05-19' union all
select 10017235,316.9,'2011-06-07' union all
select 10017235,366.9,'2011-08-19' union all
select 10017235,249.6,'2011-08-31' union all
select 10017235,107.1,'2011-09-30';with maco as
(
select row_number() over (order by (select 1)) as no,* from @t
),m1 as
(
select
a.*,datediff(d,a.[日期],b.[日期]) as 相差值
from maco a left join maco b on a.no=b.no-1
)
/*
select * from m1
no ID 金额 日期 相差值
-------------------- ----------- ------------------------------ ----------------------- -----------
1 10017235 115.4 2011-04-21 00:00:00.000 0
2 10017235 99.9 2011-04-21 00:00:00.000 28
3 10017235 279.0 2011-05-19 00:00:00.000 19
4 10017235 316.9 2011-06-07 00:00:00.000 73
5 10017235 366.9 2011-08-19 00:00:00.000 12
6 10017235 249.6 2011-08-31 00:00:00.000 30
7 10017235 107.1 2011-09-30 00:00:00.000 NULL
*/select sum(相差值)*1.0/count(相差值) from m1
/*
27
*/
go
create table [tb]([ID] int,[金额] numeric(4,1),[日期] datetime)
insert [tb]
select 10017235,115.4,'2011-4-21' union all
select 10017235,99.9,'2011-4-21' union all
select 10017235,279,'2011-5-19' union all
select 10017235,316.9,'2011-6-7' union all
select 10017235,366.9,'2011-8-19' union all
select 10017235,249.6,'2011-8-31' union all
select 10017235,107.1,'2011-9-30'
go--sql2000借助一个临时表
select *,rn=identity(int,1,1) into # from tb
goselect avg(datediff(dd,a.日期,b.日期)) as num
from # a
left join # b on a.id=b.id and a.rn=b.rn-1--drop table #