Вы можете сделать это, используя несколько подзапросов, как показано ниже.
DECLARE @SampleTable TABLE
(
Date DATETIME,
Type VARCHAR(100),
TransId VARCHAR(100),
Qty INT,
UnitCost MONEY,
Total MONEY
)
INSERT INTO @SampleTable VALUES
('2020-01-01', 'OPEN', 'IN33433', 100 , 12 , 1200 ), --IN,UnitCost is fixed
('2020-03-19', 'PUR', 'IN31134', 200 , 12.5 , 2500 ), --IN,UnitCost is fixed
('2020-03-21', 'DEL', 'OUT24443', 250 , 12.33 , 3082.5), --OUT unit cost calculated
('2020-03-25', 'DEL', 'OUT28668', 10 , 12.33 , 123.3 ), --OUT unit cost calculated
('2020-03-26', 'SAL', 'OUT35448', 23 , 12.33 , 283.59), --OUT unit cost calculated
('2020-03-30', 'TRSFR', 'IN83588', 12 , 12.45 , 149.4 ) --IN, UnitCost is fixed
SELECT
*,
(SELECT SUM(Total) FROM @SampleTable S2 WHERE S2.Date < S1.Date AND S2.TransId LIKE 'IN%' AND S1.TransId LIKE 'OUT%') AS SumOutTransaction,
(SELECT SUM(Qty) FROM @SampleTable S2 WHERE S2.Date < S1.Date AND S2.TransId LIKE 'IN%' AND S1.TransId LIKE 'OUT%') AS SumQtyTransaction,
CASE
WHEN S1.TransId LIKE 'OUT%' THEN
(
(SELECT SUM(Total) FROM @SampleTable S2 WHERE S2.Date < S1.Date AND S2.TransId LIKE 'IN%' AND S1.TransId LIKE 'OUT%')
/
(SELECT SUM(Qty) FROM @SampleTable S2 WHERE S2.Date < S1.Date AND S2.TransId LIKE 'IN%' AND S1.TransId LIKE 'OUT%')
)
ELSE Total/Qty
END AS CalculatedUnitCost
FROM @SampleTable S1
Кроме этого, могут быть и другие, более оптимизированные варианты.