2

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

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

4

1 回答 1

2

按 FK 对行进行分组,选择FKand Max(date) as MaxDate,然后将结果加入到同一张表中,FK=FK并且date=maxDate(希望每个 FK 的日期不相等)
如果每个 FK 的日期确实相等,那么看看另一个我的答案

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
于 2013-11-14T20:53:17.823 回答