[英]Update date column from min date in another column in the same table
I need to update a field called "FirstPayment" with the date from another field in the same table. 我需要使用同一张表中另一个字段的日期来更新一个名为“ FirstPayment”的字段。
Here is the code: 这是代码:
UPDATE R1
SET R1.FirstPayment = (select min(r1.effective_date) where R1.amount>0)
from CTTC_RentalCarPayments R1, CTTC_RentalCarPayments R2
where r1.id=r2.id
This results in "An aggregate may not appear in the set list of an UPDATE statement" 这导致“聚合可能不会出现在UPDATE语句的设置列表中”
I know I am missing something simple here. 我知道我在这里缺少一些简单的东西。
I also know the FirstPayment field isn't necessary because I could get that date in a query but the application I am feeding this data too needs it in this column. 我也知道FirstPayment字段不是必需的,因为我可以在查询中获得该日期,但是我要提供此数据的应用程序也需要此列。
Use window functions: 使用窗口功能:
with toupdate as (
select r.*,
min(case when r1.amount > 0 then r.effective_date end) over (partition by id) as new_effective_date
from CTTC_RentalCarPayments r
)
update toupdate
set FirstPayment = new_effective_date;
You could set value of the field you want to get to a variable and then update the field to that variable: 您可以设置要获取变量的字段的值,然后将该字段更新为该变量:
Declare @firstPayment datetime;
Set @firstPayment = (select min(r1.effective_date) from r1 where R1.amount>0);
Declare @firstPaymentID int;
Set @firstPaymentID = (select id from r1 where @firstPayment = FirstPayment);
UPDATE r1
SET FirstPayment = @firstPayment where Id = @firstPaymentID;
Let me know if this helps. 让我知道是否有帮助。 It's not a recursive CTE but it might work too. 它不是递归的CTE,但也可能有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.