Suppose I have the following table:
CustomerId | Amount | Date | LastMonthDate | SumLastMonthAmount |
---|---|---|---|---|
1 | 500 | 20220301 | 20220201 | 500 |
1 | 200 | 20220304 | 20220204 | 700 |
1 | 400 | 20220320 | 20220220 | 1100 |
1 | 100 | 20220329 | 20220229 | 1200 |
1 | 100 | 20220402 | 20220302 | 800 |
As you can see, I want to have sum of amount for last month; suppose that SumLastMonth
is NULL
in the table, how should I update this column?
Note that you can't use date functions at all. and our date columns have int type as you see
The query that I wrote for this task is:
UPDATE A
SET SumLastMonthAmount = (SELECT SUM(Amount)
FROM Table B
WHERE A.CustomerId = B.CustomerId
AND B.Date > A.LastMonthDate
AND B.Date <= A.Date)
FROM Table A
Where A.Date=20220402
But it is very slow. Can you suggest a better query?