0

I have information in base tables which is like this.

ORDER# Date Item Qty Onhand Avl Fill
100030505 2024-11-19 862181010 84.00000 164 80
100030505 2024-11-20 862181010 85.00000 164 -5
100030505 2024-11-21 862181010 86.00000 164 -91
100030505 2024-11-22 862181010 87.00000 164 - 178

I need to calculate a column based on this that would show line by line Onhand-Qty based on previous line. For example: 1st row would give as (164-84) = 80 2nd row would give me 80-85 = -5 and so on. It is based on item and date. If item would change, then the counter should restart.

How can I achieve this in Oracle SQL?

Need to calculate Avail_to_fill in this.

4
  • @DaleK I have added additional column to be derived. Commented May 8 at 4:34
  • 1
    @DaleK Added, Please check. Commented May 8 at 4:35
  • 2
    Why did you add the MySQL tag again? It's a totally different product to Oracle! Commented May 8 at 6:22
  • As per the linked duplicate: SELECT t.*, onhand - SUM(qty) OVER (PARTITION BY order#, item ORDER BY date_column) AS avl_fill FROM table_name t Commented May 8 at 7:15

1 Answer 1

2

You can use analytic functions to solve this problem. Here's the scripts:

create table tmp(
    ord INT,
    dt DATE,
    itm INT,
    qty DOUBLE PRECISION,
    onhand INT
);

insert into tmp values(100030505, DATE '2024-11-19', 862181010, 84.00000, 164);
insert into tmp values(100030505, DATE '2024-11-20', 862181010, 85.00000, 164);
insert into tmp values(100030505, DATE '2024-11-21', 862181010, 86.00000, 164);
insert into tmp values(100030505, DATE '2024-11-22', 862181010, 87.00000, 164);


select ord, dt, itm, qty, onhand,
        onhand - SUM(qty) OVER (
        PARTITION BY ord, itm 
        ORDER BY dt 
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS AvlFill
from tmp;

The result is as below:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.