SQL Server Assign the SUM value to the MAX date present for that ID using SQL in SSMS

pxy2qtax  于 2023-08-02  发布在  其他
关注(0)|答案(1)|浏览(148)

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.

  1. SELECT
  2. ID,
  3. Date,
  4. SUM([RequiredQty]),
  5. SUM([ReceivedQty]),
  6. SUM([RequiredQty]) - SUM([ReceivedQty]) AS outstanding_qty
  7. FROM
  8. Dff d
  9. INNER JOIN
  10. (SELECT ID, MAX(Date) AS max_date
  11. FROM dff d
  12. GROUP BY ID) grd ON d.ID = grd.ID
  13. AND d.Date = grd.max_date
  14. GROUP BY
  15. 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:

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

I should get

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

but I get

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

qpgpyjmq1#

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:

  1. DECLARE @Table TABLE (ID BIGINT IDENTITY, Date DATE, RequiredQuantity INT, ReceivedQuantity INT, OutstandingQuantity AS RequiredQuantity - ReceivedQuantity);
  2. INSERT INTO @Table (Date, RequiredQuantity, ReceivedQuantity) VALUES
  3. ('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.

  1. SELECT *, CASE WHEN Date = MAX(Date) OVER (ORDER BY (SELECT 1)) THEN SUM(OutstandingQuantity) OVER (ORDER BY (SELECT 1)) END AS TotalOutstandingQuantity
  2. 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.

IDDateRequiredQuantityReceivedQuantityOutstandingQuantityTotalOutstandingQuantity
12023-06-04211
22023-06-057434
展开查看全部

相关问题