Get new customers every week in SQL Server -
i have data related customers , number of transactions perform every day. see how many "new" customers each week. data looks following:
custnum created revenue 1 2014/10/23 30 4 2014/10/23 20 5 2014/10/23 40 2 2014/10/30 13 3 2014/10/30 45 1 2014/10/30 56
in above (sample) data, can see customer custnum
1 has transactions in consecutive weeks, want new customers next week, ones have never done business in past. in other words, want number of totally new customers each week. result should be:
custcount created 3 2014/10/23 2 2014/10/30
i tried using following query:
select count(distinct custnum), dateadd(wk, datediff(wk, 0, created), 0) date orders created > '2013-01-01' group dateadd(wk, datediff(wk, 0, created), 0) order dateadd(wk, datediff(wk, 0, created), 0)
but query gives me number of unique customers each week, want number of new customers every week.
any appreciated.
my understanding of question
i took these statements:
- i see how many "new" customers each week.
- [customers] have never done business in past
- i want number of totally new customers each week
do want
custcount created 2 week1 -- customer 1 , 2 1 week2 -- customer 3 2 week3 -- customer 4 , 5 -- option 1 week4 -- customer 6 new , 2 not counted -- or option b 2 week4 -- customer 6 , 2; -- since customer 2 did not order in week3
option a
this query select custnum, datepart ( week , created) weeknumber revenues order custnum
returns output provided sample data
custnum weeknumber 1 31 -- counts 1 44 -- not count, since customer ordered once 2 36 -- counts 3 36 -- counts 3 44 -- not count 4 43 -- counts 5 43 -- counts 5 45 -- not count
first step: filter down records
to first record customer (the new customer) can this:
select distinct custnum, min(created) min_created revenues group custnum
second step: counting , grouping week
first used sql grouping customer orders week, can find @ old sqlfiddle . decided use
select count(custnum) countcust , datepart(week, min_created) week_min_created ( select distinct custnum, min(created) min_created revenues group custnum ) sq group datepart(week, min_created)
on sql-server-2008-r2 returns
countcust week_min_created 1 31 -- customer 1 2 36 -- customer 2 , 3 2 43 -- customer 4 , 5 -- nothing week 45 since customer 5 counted
some sample data
this sample data used
create table revenues ( custnum int , created datetime, revenue int ); insert revenues (custnum, created, revenue) values (1, '20140801', 30), (2, '20140905', 13), (3, '20140905', 45), (4, '20141023', 20), (5, '20141023', 40), (3, '20141030', 45), (1, '20141030', 56), (5, '20141106', 60);
Comments
Post a Comment