Skip to content
Advertisement

Cumulative calculation using SQL

I have a supply and a demand table as shown below,

write a SQL code to get the output as shown below,

Expected output,

For a center1, if there is request-1 which came in asking for 300 units on 1-Aug but there is no supply available as of 1-Aug, so we cant fulfill the request until we get a supply. Next, supply received only on 1-Sep with 500 units. So, for the request-1, supply will happen on 1-Sep and 300 units will be supplied, so 200 is still remaining.

Now, the next request-2 on 15-Aug requires 250 units and since still 1-Sep can fulfill another 200 units of supply left over after using for req-1 we split the fulfillment for request by stating Req-2 can be fulfilled by 200 units on 1-Sep and remaining 50 only on 1-Dec when the next supply comes and so on.

Tried using while loop in Stored procedure but it takes more time when processing millions of rows. so either a function or sql needs to be written

Expected output,

Advertisement

Answer

Here is one way of looping over the data to get the desired outcome.

Essentially I have built a series of handling tables. One for filtering each demand and supply row at a time and one for actually manipulating the counts of things supplied/in demand rows, this is done so the data itself can be left alone. Finally there is a table created on the fly to generate the output itself.

The loop basically continues until there is nothing left to filter for and if anything is still outstanding either from a supply row or a demand row then that is also interted in to the output table. On each pass the current requirement and supplier handler tables are queried to see if something new needs adding, then at the end of the loop after the output row has been generated anything which is at 0 or less is removed from the handler tables to ensure only one supply or demand row is being dealt with at a time.

EDIT: I’ve added a loop for the center. This means that a data set with multiple centers will now run successfully.

I’ve also tested the example with more rows. With 48 supply records and 80 demand records this query produces 128 transaction rows in one second so I suspect the performance issues you were noticing may have had to do with the center looping rather than the query performance itself. Let me know how you get on with the updated query and if there are performance issues we can look in to why that is.

Please see example query and data using the Center1 and Center 2 data provided from your comment and output result set pasted below query.

enter image description here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement