2013-05-09 91 views
3

我有一個查詢我們可以用行數替換列的所有值嗎?

select name,name_order from name_table where dept_id=XXX; 

和結果集中是

+------------+--------+ 
| name_order | name | 
+------------+--------+ 
| 0  | One | 
| 1  | Two | 
| 2  | Three | 
| 3  | four | 
| 6  | five | 
| 9  | six | 
+------------+--------+ 

我必須更新用於的dept_id的name_order,以這樣的方式使得它們從0和 遞增開始(針對的dept_id只)
注:name_order是不是索引
的出落得應該像

+------------+--------+ 
| name_order | name | 
+------------+--------+ 
| 0  | One | 
| 1  | Two | 
| 2  | Three | 
| 3  | four | 
| 4  | five | 
| 5  | six | 
+------------+--------+ 

我試圖分析功能ROWNUMBER(),它並沒有幫助提前

update name_table set name_order = (
ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY name_order)-1 
) 
where dept_id=XXX order by name_order 

感謝 -R

回答

0
UPDATE NAME_TABLE A 
SET NAME_ORDER=(
    SELECT R 
    FROM (SELECT NAME,ROW_NUMBER() OVER(ORDER BY NAME_ORDER) R 
       FROM NAME_TABLE) B 
    WHERE A.NAME=B.NAME); 

http://www.sqlfiddle.com/#!4/6804a/1

UPDATE NAME_TABLE A 
SET NAME_ORDER=(
    SELECT R 
    FROM (SELECT NAME,DEPT_ID,ROW_NUMBER() OVER(PARTITION BY DEPT_ID ORDER BY NAME_ORDER)-1 R 
       FROM NAME_TABLE) B 
    WHERE A.NAME=B.NAME AND A.DEPT_ID=B.DEPT_ID /*AND A.DEPT_ID=XXX*/); 

添加有關條件dept_id爲。謝謝路人。

+1

這會更接近OP的問題:http://www.sqlfiddle.com/#!4/f02c1/2 – Passerby 2013-05-09 05:45:15

+0

@Passerby是的,我沒有不考慮dept_id.I更新我的答案。 – Gentlezerg 2013-05-09 05:58:30

-3
SET @rownum:=0; SELECT @rownum:[email protected]+1 AS name_order, names from name_table where dept_id=XXX; 

working fine on mysql. 
+0

這甚至不適用於Oracle的有效語法。 – Mat 2013-05-09 05:22:13

+0

同樣謝謝。當我在oracle上運行時,第26行:SQLPLUS Command Skipped: – 2013-05-09 05:31:32

2

您可以用merge command

MERGE INTO name_table dst 
USING (SELECT t.*, row_number() over (partition BY dept_id ORDER BY name_order) -1 n 
     FROM name_table t) src 
ON (dst.dept_id = src.dept_id AND dst.name = src.name) 
WHEN MATCHED THEN UPDATE SET Dst.name_order = src.n; 

Here is a sqlfiddle demo

做,但爲什麼你想與值的列,你可以在查詢?

+0

他可以將其用作此數據的UI輸出的任意排序鍵,可以通過這種方式進行初始化並稍後進行更改。 – 2013-05-09 05:45:43

+0

實際上,我使用這些列值作爲索引(但它並非實際索引)在JPA多對多關係中進行排序,這導致null對象缺少name_order – 2013-05-09 05:50:32

+0

(儘管我們在java側有一個修復程序)來修復損壞的數據在數據庫我想復活列值 – 2013-05-09 05:52:04

相關問題