SQL, compute the inventory capacity

In SQLite, process_table table stores inventory information. arrivals field is the tonnage arrived, and max_output_capacity is the maximum inventory tonnage. In theory, the arrivals in each day should be less than max_output_capacity, otherwise not all cargo can enter into the warehouse on the current day and the rest of the cargo should be taken on the next day.

day

arrivals

max_output_capacity

0

0

2

1

2

3

2

5

4

3

0

5

4

0

5

5

14

1

6

0

3

7

1

2

8

1

12

Now we need to add a computed column named remaining_next_day to get the amount of tonnage that cannot enter the warehouse on the current day but will be entered on the next day.

day

arrivals

max_output_capacity

remaining_next_day

0

0

2

0

1

2

3

0

2

5

4

1

3

0

5

0

4

0

5

0

5

14

1

13

6

0

3

10

7

1

2

9

8

1

12

0

Here is the SPL code:

=sqliteDB.query("select * from process_table order by day")

.derive(if((t=remaining_next_day[-1]+arrivals-max_output_capacity)>0,t,0):remaining_next_day)

derive function adds a computed column; [-1] represents the directly previous record.

Source:https://www.reddit.com/r/SQL/comments/1c865t8/query_to_calculate_the_remaining_units_to_the/