I’ve the following table (both A and B are integers):
Update 1 – Could anyone do me a favour and run the solution on a set of 1M records with B being a random decimal (to avoid overflows) residing in [0 to 1] range for N=> 10, 100 and 1000? I’d like to get a flavor of the time, required to run the solution query. Thanks a lot in advance.
Sample data:
A B
1 1
2 8
3 1
4 11
5 1
6 1
7 6
8 1
9 1
10 2
How do I get the maximum Sum of B values for any N sequential A‘s? The solution mustn’t use cursors, usage of table vars/tem tables has to be stongly justified.
I can use SQLCLR in case if it’ll give a distinct performance boost.
Some clarifications:
- Max Sum for 1 element is 11 (see A = 4)
- Max Sum for 2 elements is 12 (it’s either A=> 1 & 2 or A=> 2 & 3),
- Max Sum for 3 elements is 20 (A=>2, 3, 4),
- Max Sum for 4 is 21 (A=>1,2,3,4 or A=>2,3,4,5) etc.
Since the
Avalues are guaranteed to be consecutive integers, givenNwe know for any particularAwhich values we are interested in. Sogives, for each
A, the sum of theBvalues for theNrows starting there. TheWHERErestricts us to rows that do actually haveNrows starting there. Put this in a subquery and we can get the maximum:should do the job.