0

I have got RequiredQty (A) and ReceivedQty (B) for ID along with dates. I want to sum A and sum B, subtract the difference for each ID and assign this difference to the MAX or LATEST date.

SELECT      
    ID,
    Date,   
    SUM([RequiredQty]),
    SUM([ReceivedQty]),
    SUM([RequiredQty]) - SUM([ReceivedQty]) AS outstanding_qty
FROM 
    Dff d
INNER JOIN
    (SELECT ID, MAX(Date) AS max_date 
     FROM dff d  
     GROUP BY ID) grd ON d.ID = grd.ID 
                      AND d.Date = grd.max_date
GROUP BY
    ID, Date

I was expecting:

for ID = 1, my max date is 5th June, so I should get difference of both those summed up columns next to it, but instead I am getting the exact values of 5th June.

Example:

ID :: date     :: A :: B :: outstanding_qty
----------------------------------------
 1 :: 4th June :: 2 :: 1 :: 1
 1 :: 5th June :: 7 :: 4 :: 3

I should get

ID :: date     :: A :: B :: outstanding_qty
--------------------------------------------
1 :: 5th June :: 9 :: 5 :: 4 

but I get

ID :: date    :: A :: B :: outstanding_qty
-------------------------------------------
1 :: 5th June :: 7 :: 4 :: 3
Dale K
  • 25,246
  • 15
  • 42
  • 71

1 Answers1

0

When asking questions like this, it's really helpful to include example DDL/DML. I was able to infer it from your description, I think:

DECLARE @Table TABLE (ID BIGINT IDENTITY, Date DATE, RequiredQuantity INT, ReceivedQuantity INT, OutstandingQuantity AS RequiredQuantity - ReceivedQuantity);
INSERT INTO @Table (Date, RequiredQuantity, ReceivedQuantity) VALUES
('2023-06-04', 2, 1), ('2023-06-05', 7, 4);

I cheated a little here, and used a computed column, since the value is dependent on the other two.

SELECT *, CASE WHEN Date = MAX(Date) OVER (ORDER BY (SELECT 1)) THEN SUM(OutstandingQuantity) OVER (ORDER BY (SELECT 1)) END AS TotalOutstandingQuantity
  FROM @Table

This uses windowed functions to find the max date, and the total outstanding quantity, and then uses a case expression to only display them on the last date. ORDER BY (SELECT 1) is a kluge, but it works for this.

ID Date RequiredQuantity ReceivedQuantity OutstandingQuantity TotalOutstandingQuantity
1 2023-06-04 2 1 1
2 2023-06-05 7 4 3 4
Patrick Hurst
  • 2,086
  • 1
  • 3
  • 13