I'm using SQL Server 2019, I have a table with rows containing amounts, and I need to adjust/deduct each row from the total while maintaining a running balance. I'm looking for a query that will give me two columns value:
- Adjusted: The deducted or adjusted value from the total.
- Balance: The remaining total value after adjustment.
Please note that in the example below, the total is fully adjusted for IDs 1 and 2, while for ID 3, only the remaining balance is adjusted, at the same time ID 4 no value adjusted due to zero remaining balance. What would be the most efficient query to achieve this result?
TOTAL = 1000.00
Id Amount Adjusted Balance
-----------------------------------------------
1 150.00 150.00 850.00
2 250.00 250.00 600.00
3 700.00 600.00 0.00
4 450.00 0.00 0.00
This is the script for my table:
DECLARE @TotalAmount FLOAT=1000
DROP TABLE IF EXISTS [#MyTable];
SELECT Id, Amount, Adjusted, Balance
INTO [#MyTable]
FROM
(SELECT (1)Id,(150.00)Amount,(0.00)Adjusted,(0.00)Balance union
SELECT (2)Id,(250.00)Amount,(0.00)Adjusted,(0.00)Balance union
SELECT (3)Id,(700.00)Amount,(0.00)Adjusted,(0.00)Balance union
SELECT (4)Id,(450.00)Amount,(0.00)Adjusted,(0.00)Balance
) [MyTable];
SELECT * FROM [#MyTable]
1条答案
按热度按时间0mkxixxg1#
You can do something like this using the sum aggregate:
There are a couple of CASE WHENs:
CASE WHEN @TotalAmount - runningSum >= 0 THEN Amount WHEN runningSum -Amount >= @TotalAmount THEN 0 ELSE @TotalAmount - runningSum + Amount END
This takes case of three cases:
CASE WHEN runningSum > @TotalAmount THEN 0 ELSE @TotalAmount - runningSum END
This take care of two cases: