Given a table of user points earned, I need to calculate a six month half-life of the cumulative points earned. That is, all points earned in the past 6 months are valued at 100%, 6-12 months at 50%, 12-18 months %25, etc.
Here is my best attempt using a CTE:
DECLARE @t AS TABLE (
ID int NOT NULL,
DT SMALLDATETIME NOT NULL,
POINTS int NOT NULL,
UserId INT NOT null,
POINTS_TOTAL INT NOT NULL)
INSERT INTO @t
VALUES (1, '1/1/2010', 20, 1, 20)
,(5, '7/1/2010', 30, 1, 50)
,(7, '1/1/2011', 10, 1, 60)
,(8, '7/1/2011', 15, 1, 75)
,(9, '12/25/2011', 15, 1, 90)
;WITH ctePts AS
(SELECT t.*, POINTS AS Decay
FROM @t AS t
WHERE t.DT > DATEADD(mm, 6, GETUTCDATE())
UNION ALL
SELECT t.ID, t.DT, t.POINTS, t.UserId, t.POINTS_TOTAL, CAST(ctePts.Decay * 0.5 + t.POINTS AS INT) AS Decay
FROM ctePts
INNER JOIN @t AS t
ON t.UserId = ctePts.UserId
AND t.DT <= ctePts.DT AND t.DT > DATEADD(mm, 6, ctePts.DT)
)
SELECT *
FROM ctePts
The final table would have a HALF_LIFE column that contains the adjusted sum of all points earned for that user. I should be able to run the following query to get the user’s current point status (total accumulated points those adjusted for half-life decay) for any given point in time:
SELECT UserIdInt, POINTS, POINTS_HALFLIFE FROM
(SELECT UserIdInt,
ISNULL(p.POINTS_TOTAL,0) AS POINTS, ISNULL(p.POINTS_HALFLIFE,0) POINTS_HALFLIFE,
ROW_NUMBER() OVER (Partition BY UserIdInt ORDER BY p.ID DESC) AS rownum
FROM dbo.USER_POINTS p ) a
WHERE rownum = 1
Is this what you need?
Returns