我们可以用行号替换列的所有值吗?

时间:2013-05-09 05:01:39

标签: sql oracle oracle10g

我有一个查询

select name,name_order from name_table where dept_id=XXX;

,resultSet为

+------------+--------+
| 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

3 个答案:

答案 0 :(得分: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

但是为什么你想要一个包含查询中可以拥有的值的列呢?

答案 1 :(得分: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的条件。谢谢Passerby。

答案 2 :(得分:-3)

SET @rownum:=0; SELECT @rownum:=@rownum+1 AS name_order, names from name_table where dept_id=XXX;

working fine on mysql.