I'm using SQL Server 2012 to extract rolling sales info for sales agents. These agents are paid bonuses if they achieve 15 sales within a rolling time period of 6 or less days. If they make target, the rolling count resets. Sundays should be ignored.
So given the following AgentID, Date and Sales data:
SELECT 1 AgentID,'2016-10-31' Date,1 Sales
INTO #Sales
UNION SELECT 1,'2016-11-01',2
UNION SELECT 1,'2016-11-02',1
UNION SELECT 1,'2016-11-03',5
UNION SELECT 1,'2016-11-04',3
UNION SELECT 1,'2016-11-05',2
UNION SELECT 1,'2016-11-07',6
UNION SELECT 1,'2016-11-08',5
UNION SELECT 1,'2016-11-09',4
UNION SELECT 1,'2016-11-10',6
UNION SELECT 1,'2016-11-11',1
UNION SELECT 1,'2016-11-12',3
UNION SELECT 1,'2016-11-14',2
UNION SELECT 1,'2016-11-15',2
UNION SELECT 1,'2016-11-16',4
UNION SELECT 1,'2016-11-17',2
UNION SELECT 1,'2016-11-18',2
The Dates that I expect the target to be hit are:
2016-11-07 (period 2016-11-01 -> 2016-11-07)
2016-11-10 (period 2016-11-08 -> 2016-11-10)
2016-11-18 (period 2016-11-12 -> 2016-11-18)
AgentID Date Sales Qualify
-------------------------------
1 2016-10-31 1 0
1 2016-11-01 2 0
1 2016-11-02 1 0
1 2016-11-03 5 0
1 2016-11-04 3 0
1 2016-11-05 2 0
1 2016-11-07 6 1
1 2016-11-08 5 0
1 2016-11-09 4 0
1 2016-11-10 6 1
1 2016-11-11 1 0
1 2016-11-12 3 0
1 2016-11-14 2 0
1 2016-11-15 2 0
1 2016-11-16 4 0
1 2016-11-17 2 0
1 2016-11-18 2 1
I've tried a few approaches but I can't find a way to reset the rolling totals.
I think that window functions are the way to go.
Looking at posts like Window Functions - Running Total with reset
I think this is similar to what I need but can't quite get it to work correctly.
UPDATE: The first thing I tried was to create rolling 6 day windows but I don't see this working in a set-based approach. I could use a cursor to step through these rows but I really don't like the idea.
SELECT DATEADD(DAY,-6,a.Date) StartDate,Date EndDate,a.AgentID,a.Sales,
(SELECT SUM(b.Sales)
FROM cteSales b
WHERE b.Date <= a.Date
AND b.Date >= DATEADD(DAY,-6,a.Date)) TotalSales
FROM cteSales a
I then tried to use the script mentioned in the URL above but I don't really understand what it's doing. I'm just changing things in the hope of stumbling across the solution and that just isn't working.
WITH c1 as
(
select *,
sum(sales) over(order by IDDate rows unbounded preceding) as rt
from cteSales
)
SELECT date, sales, rt,
SalesTarget_rt - lag(SalesTarget_rt, 1, 0) over(order by date) as SalesTarget,
rt * SalesTarget_rt as new_rt
from c1
cross apply(values(case when rt >= 15 then 1 else 0 end)) as a1(SalesTarget_rt);