一张表我要统计所有会员首次购买,二次购买,和三次购买,以及四次及以上购买,和重复购买(除首次购买的该客户所有购买,同时这一次,二次,三次是以天为单位的,一个客户同一天内的所有购买都算一次购买)
1.人数 2.金额(比如只有两个人有二次购买,这金额就是他们两个第二次购买的总和),件数,单数
一个人一天算一单
我做的中间表大致是
customerid sales create_time item_num counter
2013-08-12 12:34:33 889
统计 首次购买 二次购买 三次购买 以及四次及以上购买 重复购买
customer #
sales
item
单数
------解决思路----------------------
楼主这个貌似应该是先根据你的条件统计好,再来一个行转列应该就可以了
------解决思路----------------------
问题不明,不知道楼主要统计什么.做一个表的预整理吧.
create table t1(cid int,sales decimal(18,2),create_time datetime,item_num int,counter int)
go
insert into t1
select 1,100,'2013-08-12 12:34:33',1,3 union all
select 1,200,'2013-08-12 15:34:33',2,5 union all
select 1,90,'2013-08-12 18:34:33',1,2 union all
select 1,300,'2013-08-13 12:34:33',3,7 union all
select 1,300,'2013-08-13 22:34:33',3,7 union all
select 1,280,'2013-08-15 12:34:33',3,4 union all
select 1,220,'2013-08-18 12:34:33',5,8 union all
select 1,170,'2013-08-22 12:34:33',2,5 union all
select 1,150,'2013-08-26 12:34:33',2,4 union all
select 1,330,'2013-09-15 12:34:33',3,6 union all
select 2,200,'2013-08-13 12:34:33',3,5 union all
select 2,300,'2013-08-15 12:34:33',5,9 union all
select 2,500,'2013-08-18 12:34:33',7,10
go
select cid,sum(sales)as sumoneday,count(*)ctoneday,convert(varchar(10),create_time,120) as dt,sum(item_num) as sumitem,sum(counter) as sumct
into #1
from t1 group by cid,convert(varchar(10),create_time,120)
select *,购买次数=row_number()over(partition by cid order by dt) from #1
/*
cid sumoneday ctoneday dt sumitem sumct 购买次数
----------- --------------------------------------- ----------- ---------- ----------- ----------- --------------------
1 390.00 3 2013-08-12 4 10 1
1 600.00 2 2013-08-13 6 14 2
1 280.00 1 2013-08-15 3 4 3
1 220.00 1 2013-08-18 5 8 4
1 170.00 1 2013-08-22 2 5 5
1 150.00 1 2013-08-26 2 4 6
1 330.00 1 2013-09-15 3 6 7
2 200.00 1 2013-08-13 3 5 1
2 300.00 1 2013-08-15 5 9 2
2 500.00 1 2013-08-18 7 10 3
*/
go
drop table t1,#1