使用最后一行字段值更新字段

发布于 2025-02-10 19:27:04 字数 1992 浏览 0 评论 0原文

客户数量日期lastmonthdatesumlastmonthamount
150020220301202202015001
20020220304202204700
140020220320220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220200假设
202204

​上个月;假设SumlastMonthnull在表中,我应该如何更新此列?

请注意,您根本不能使用日期功能。当您看到

我为此任务写的查询时,我们的日期列具有INT类型:

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

但是它非常慢。您可以建议一个更好的查询吗?

Suppose I have the following table:

CustomerIdAmountDateLastMonthDateSumLastMonthAmount
15002022030120220201500
12002022030420220204700
140020220320202202201100
110020220329202202291200
11002022040220220302800

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情魔剑神 2025-02-17 19:27:04

您的代码被修改如下。如果未确定上个月的“上个月”金额为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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文