Hi,I have a table like below which is for customers and their accounts. Accounts for each customer is sorted based on their priority column , balance and some other factors via clustered index.I need to deduct from customer's accounts (CIFNO)20$ according to their total balance ,for each of their accounts based on the current order. the output should be a table like this: that it has deducted each account the max value below 20$ and if it does not meet 20$ goes through next accounts until it meets 20$ or if the totsl sum of all accounts balance is below the 20$ it deducts as much as possible.Thank youBALANCE branch TBTYPE CIFNO SERIAL priority Amount7 101 800 1 3 1 75 101 800 1 1 1 55 101 800 1 2 1 52 101 12 1 3 2 2100 101 700 1 3 3 18 101 800 2 3 1 85 101 800 2 1 1 52 101 813 2 2 1 23 101 12 2 3 2 33 101 700 2 3 3 210 101 800 3 3 1 105 101 800 3 1 1 54 101 12 3 3 2 420 101 700 3 3 3 110 101 700 3 3 3 0
I need a fast solution with single update statement , since there are a lot of records in the table.I tryed this code but it doesn't work correctlyDECLARE @Prevcif DECIMAL( 8,0) =0 DECLARE @Runningamnt DECIMAL( 18,0) =0 DECLARE @Base DECIMAL(18,0) = 20UPDATE dbo.[mytable]SET @Runningamnt = [Amount] = CASE WHEN [CIFNO] = @Prevcif THEN CASE WHEN balance > = (@Base - @Runningamnt) THEN @Base - @Runningamnt ELSE balance END ELSE CASE WHEN balance >= @Base THEN @Base ELSE balance END END, @Prevcif = [CIFNO]
DROP TABLE [mytable]CREATE TABLE [dbo].[mytable]( [BALANCE] [decimal](18, 0) NULL, [branch] [decimal](4, 0) NOT NULL, [TBTYPE] [decimal](3, 0) NOT NULL, [CIFNO] [decimal](8, 0) NOT NULL, [SERIAL] [decimal](3, 0) NOT NULL, [priority] [int] NOT NULL, [Amount] [decimal](18, 0) NULL ) ON [PRIMARY]CREATE UNIQUE CLUSTERED INDEX [OrderdByDEPandBal] ON [dbo].[mytable] ( [CIFNO] ASC, [priority] ASC, [BALANCE] DESC, [branch] ASC, [TBTYPE] ASC, [SERIAL] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]GOINSERT INTO [mytable] SELECT 7,101,800,1,3,1,NULL UNION SELECT 5,101,800,1,1,1,NULL UNIONSELECT 5,101,800,1,2,1,NULL UNIONSELECT 2,101,12,1,3,2,NULL UNIONSELECT 100,101,700,1,3,3,NULL UNIONSELECT 8,101,800,2,3,1,NULL UNION SELECT 5,101,800,2,1,1,NULL UNIONSELECT 2,101,813,2,2,1,NULL UNIONSELECT 3,101,12,2,3,2,NULL UNIONSELECT 3,101,700,2,3,3,NULL UNIONSELECT 10,101,800,3,3,1,NULL UNION SELECT 5,101,800,3,1,1,NULL UNIONSELECT 4,101,12,3,3,2,NULL UNIONSELECT 20,101,700,3,3,3,NULL UNIONSELECT 10,101,700,3,3,3,NULL