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?
your code is modified as below. if last month is not identified "last Month amount" will be null
with cte as(
select A.CustomerId , A.LastMonthDate, A.Date,SUM(B.Amount) as newLastMonthAmount
from Table A
left Join Table B
on A.CustomerId = B.CustomerId
AND B.Date > A.LastMonthDate
AND B.Date <= A.Date
group by A.CustomerId , A.LastMonthDate, A.Date
)
update A
set SumLastMonthAmount=B.newLastMonthAmount
from Table A
join cte B
on A.CustomerId = B.CustomerId
AND B.Date = A.Date
AND B.LastMonthDate = A.LastMonthDate
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.