SQL Server - 具有max和group by的Update语句

时间:2016-11-08 14:53:29

标签: sql sql-server tsql

我有一个SQL Server表,其中包含这样的列,但只填充了Salary_ID列:

Name: Salary
Salary_ID, TotalAmount

我有另一个具有此格式的SQL Server表,并填充了所有列:

Name: SalaryImport
Row_ID, Salary_ID, Amount

我正在尝试更新Salary表,每个row_id的最大salary_id。目前,Salary_ID中的每个SalaryImport都有很多实例,我只关心最新的row_id更高的数据。

有关如何做到这一点的任何提示?我以为我会运行一个SQL语句,但它分组太多了(我可以从组中删除金额,因为它在选择中!):

select max(Row_ID), Salary_ID, Amount
from SalaryImport e
group by  Row_ID, Amount

1 个答案:

答案 0 :(得分:6)

使用ROW_NUMBER窗口功能

;with cte as
(
select row_number() over(partition by Salary_ID order by Row_ID desc) as rn,*
From yourtable
)
Update S
Set TotalAmount = c.Amount
From Salary s join cte c on s.Salary_ID = c.Salary_ID
Where RN = 1