简体   繁体   English

从同一表中另一列中的最小日期更新日期列

[英]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.

相关问题 从同一表中的日期列更新月份列 SQL 服务器 - update month column from date column in the same table SQL Server 根据日期和列 ID 从另一个表更新和插入 - update and insert from another table based on date and column id 从同一个表中的另一列更新列 - Update Column from another column in same table 从表的同一列中将日期作为“从日期”和“到日期” - Get date as 'from date' and 'to date' from same column in table 对表进行 LEFT JOIN 并根据另一列条件从 MIN(date) 的新表中选择列 - LEFT JOIN on a table and SELECT columns from new table of MIN(date) based on another column condition 获取最小日期和带有最小日期的另一列的第一个文本 - Get min date and first text of another column with min date 存储过程以基于最小日期更新列 - Stored procedure to update column based on Min Date 检查约束是否一个表(列)中的日期适合另一个表(列)中的另一个日期 - Check constraint whether the date from one table (column) fits to another date from another table (column) 根据表中的另一列从列中选择最大日期 - Select largest date from column based on another column in table 检索日期早于 6 个月的记录并更新同一表中的列 - Retrieve records with date older than 6 months and update a column in the same table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM