使用每个外键的最大日期更新多行

时间:2013-11-14 20:29:01

标签: sql sql-server

我可以使用以下语句选择要更新的行的信息:

select max(Date),F_ID from MyTable group by F_ID

F_ID是外键。我正在尝试更新日期最大的其他字段。问题是可能有许多行具有相同的外键和相同的日期。如果这些是最大日期有多行我想要更新所有行。

我能得到的最接近的是:

update MyTable set
Curr = 1
where (select cast(Date as varchar(20))+cast(F_ID as varchar(10)) from MyTable) in
(select cast(max(Date)as varchar(20))+cast(F_ID as varchar(10)) from MyTable group by A_PID)

我收到此错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

感谢您的帮助!

编辑:更新语句的最终查询格式,以防其他人正在寻找此内容:

update MyTable set
    Curr = 1
from MyTable t inner join
    (select F_ID,max(Date) maxDate
     from MyTable group by A_PID) t2
on t.A_PID = t2.A_PID and t.Date = t2.maxDate

感谢@Jim

1 个答案:

答案 0 :(得分:2)

按FK对行进行分组,选择FKMax(date) as MaxDate,然后将结果加入FK=FKdate=maxDate上的相同表格(希望每个FK没有相同的日期)
如果每个FK的日期确实相等,那么请查看another my answer

SELECT t1.* FROM Table t1
INNER JOIN 
    (SELECT F_ID, max(date) maxDate 
     FROM Table 
     GROUP BY F_ID) t2 
ON t1.F_ID=t2.F_ID AND t1.date=t2.maxDate