I want to achieve the below output from the given input tables.
Input Table (Bucket to be filled)
ID | FullCapacity | CurrentAmount
---+--------------+--------------
B1 | 100 | 0
B2 | 50 | 0
B3 | 70 | 0
Input Table (Filler Table)
ID | Filler
---+-------
F1 | 90
F2 | 70
F3 | 40
F4 | 20
Output table should have below showing filling process.
ID | FullCapacity | CurrentAmount
---+--------------+--------------
B1 | 100 | 90
B2 | 50 | 0
B3 | 70 | 0
---+--------------+--------------
B1 | 100 | 100
B2 | 50 | 50
B3 | 70 | 10
---+--------------+--------------
B1 | 100 | 100
B2 | 50 | 50
B3 | 70 | 50
---+--------------+--------------
B1 | 100 | 100
B2 | 50 | 50
B3 | 70 | 70
I am trying to fill this one by one from filler to bucket. Can we do this without using cursor?
Please see that we can have multiple types of buckets for example red bucket, blue bucket and red filler, blue filler. Red filler to go to red bucket, blue filler to blue and so on.
Thank you
You can do this in SQL Server 2008 like this:
You can do this using windowing functions like this:
SQL Server 2012+
All you need to do this are cumulative sums and some joins. Hence you can do this without a cursor. The idea is to use a cumulative join and then assign each filler record to one or more buckets, based on the ranges.
Using the ANSI standard syntax for cumulative sums:
This produces a mapping of each bucket and the amount of each filler that is in the bucket.
Note: it makes use of the functions
greatest()
andleast()
. These are easily replaced bycase
expressions if the functions are not available.