I have a table :
UNIQUE KEY ID Clicks INSERTDATE
1 100001 10 2011-05-14 00:00:00.000
2 100001 20 2011-05-13 00:00:00.000
3 100001 30 2011-05-18 00:00:00.000
4 100002 10 2011-05-20 00:00:00.000
5 100002 15 2011-05-24 00:00:00.000
6 100002 10 2011-05-05 00:00:00.000
I have a threshold value for clicks, lets say 20.
I need to write a T-SQL which should remove the clicks that do not meet the threshold of the accumulative Sum of clicks for each ID.
So for the above example ID “100001” has an accumulative clicks of 60 (10+20+30) but since the threshold is 20, the last record i.e. with the click value of 30 should get removed from the result.
However, the second record should still be included even though the sum at that point is > my threshold (10 + 20).
EDIT :
Another major rule that needs to be applied is that the INSERTDATE has to be ordered before performing any calculations
Any help would be much appreciated.
If I understood the question correctly, you’d like to filter on the RunningTotal for a given Id, like so:
this implies that you have a unique key field in the table, called
PK.Running sample: http://www.sqlfiddle.com/#!3/98173/11
Update
To order by Clicks instead of the primary key, just change the line
to
Running sample: http://www.sqlfiddle.com/#!3/31750/2