'How to get the age of current stock in SQL?

Using SQL Server 2019; I have a table called Stock Movements:

This Stock Movements table shows the movement of products between stockrooms (TRAN95 = I or O), sales to customers (TRAN95 = C) and new stock (TRAN95 = P or A).

Example Data:

Stockroom Product MQTY95 Date of Movement Time TRAN95
1A JY01 -1.000 2022/04/28 120010 C
1A JY01 1.000 2022/02/22 110256 A
1A JY01 2.000 2022/01/28 100510 P
1A JY01 1.000 2022/01/20 120824 I
1A JY01 -1.000 2022/01/18 132104 O
1A JY01 -4.000 2022/01/10 150110 C
1A JY01 8.000 2022/01/05 110255 P

Current stock of the product in stockroom 1A (obtained with the SUM of column MQTY95) is 6 pieces; I need to obtain the date each one of those pieces was received. Received stock can be identified by TRAN95 = P or A.

Desired output will show the quantity in stock per product, per stockroom per date recieved - essentially showing how "old" the stock is. So of the 6 JY01 products currently in stock, 1 was recieved on 2022/02/22; 2 recieved on 2022/01/28 etc.:

Stockroom Product Quantity Date of Movement Time
1A JY01 1.000 2022/02/22 110256
1A JY01 2.000 2022/01/28 100510
1A JY01 1.000 2022/01/20 120824
1A JY01 2.000 2022/01/05 110255

The last row shows 2 pieces which are the 8 pieces received on 2022/01/05 MINUS the 5 pieces sold on movements where TRAN95 = C, and the 1 piece moved to a different stockroom on movement where TRAN95 = O. It's safe to assume that each OUT move will always take from the oldest received lot.

I am using the following SQL query to get the current stock levels - but I am lost as to how to get the date the stock was received (as per the desired output):

SELECT
    STRC95 AS Stockroom,
    PNUM95 AS Product, 
    SUM(MQTY95) AS MovementQuantity
FROM
    StockMovements
GROUP BY 
    STRC95, PNUM95

Is this even possible using SQL?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source