Hi,
Sorry for the mess. Here is the code. The max that user can buy is 250.000 so customers 1-3 get left with 0 and customer 4 with 577 as user couldn't buy the entire amount as it would have exceeded 250.000. Preferably the query should stop afterwards and not proceed to check the other customers.
--===== If the test table already exists, drop it
IF OBJECT_ID('TempDB..#tmpCustomerAmount','U') IS NOT NULL
DROP TABLE #tmpCustomerAmount
CREATE TABLE #tmpCustomerAmount (
[id] [int] IDENTITY(1,1) NOT NULL,
AmountSold [decimal](13, 2) NULL,
AmountLeftWith [decimal](13, 2) NULL
)
SET IDENTITY_INSERT #tmpCustomerAmount ON
iNSERT INTO #tmpCustomerAmount (ID, AmountSold)
SELECT '1','123.00' ,0 UNION ALL
SELECT '2','130.000' ,0 UNION ALL
SELECT '3','500.00' ,0 UNION ALL
SELECT '4','700.00' ,577 UNION ALL
SELECT '5','300.00'
--===== Set the identity insert back to normal
SET IDENTITY_INSERT #tmpCustomerAmount OFF