2012-12-20 23 views
3

我想要做的是以下幾點: 我有一個表有多個作者SingleAuthor。該表有時會多次包含相同的作者。我想要做的是更新表格並添加作者特定的編號。例如:使用更新語句中的當前行

sat_name - > sat_rowNumber
弗雷迪 - > 1
Author2 - > 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 

我想要做的就是更新SingleAuthor表的sat_rowNumbernewTable.numb在當前行sat_name等於在newTablesat_name

關於如何在update語句中引用要更新的表的任何見解?

回答

6

回答你的問題是:

where newTable.sat_name = SingleAuthor.sat_name 

它會引用外部表,因爲一個子查詢超出範圍。但是,如果這是一個問題,你可以給子查詢中的一個別名。

我覺得你可以更有效地編寫查詢爲:

with toupdate as (
    select sa.*, dense_rank() over (order by sat_name) as newVal 
    from SingleAuthor sa 
) 
update toupdate 
    set sat_RowNumber = newval 

dense_rank()功能不正是你與row_number()在聚合值做。