Ric*_*ing 3 sql row-number inner-query sql-update
我要做的是以下内容:我有一个包含多位作者的表SingleAuthor.该表有时不止一次包含同一作者.我想要做的是更新表并添加作者特定的号码.例如:
sat_name - > sat_rowNumber
弗雷迪 - > 1
作者2 - > 2
弗雷迪 - > 1
AnotherOne - > 3
我已经有了查询给我这个结果:
SELECT ROW_NUMBER() OVER( ORDER BY sat_name),
sat_name
FROM SingleAuthor
GROUP BY sat_name
但问题是,我想在sat_rowNumber列中插入此数据.我带着这个问题来到这里:
UPDATE SingleAuthor SET sat_rowNumber = ( SELECT newTable.numb
FROM(
SELECT ROW_NUMBER() OVER( ORDER BY sat_name) as numb, sat_name
FROM SingleAuthor
GROUP BY sat_name) AS newTable
WHERE newTable.sat_name =) -- the current row in the to be updated table
Run Code Online (Sandbox Code Playgroud)
我想要做的就是更新SingleAuthor表的sat_rowNumber到newTable.numb在当前行sat_name等于sat_name在newTable.
有关如何在update语句中引用要更新的表的任何见解?
你的问题的答案是:
where newTable.sat_name = SingleAuthor.sat_name
Run Code Online (Sandbox Code Playgroud)
它将引用外部表,因为子查询中的那个超出了范围.但是,如果这是一个问题,您可以在子查询中给出一个不同的别名.
我认为你可以更有效地编写查询:
with toupdate as (
select sa.*, dense_rank() over (order by sat_name) as newVal
from SingleAuthor sa
)
update toupdate
set sat_RowNumber = newval
Run Code Online (Sandbox Code Playgroud)
该dense_rank()函数完全按照您row_number()在聚合值上执行的操作.