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

4

3 回答 3

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;

这是一个 sqlfiddle 演示

但是,为什么您想要一列具有您可以在查询中拥有的值?

于 2013-05-09T05:38:49.157 回答
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 的条件。谢谢路人。

于 2013-05-09T05:31:13.197 回答
-3
SET @rownum:=0; SELECT @rownum:=@rownum+1 AS name_order, names from name_table where dept_id=XXX;

working fine on mysql. 
于 2013-05-09T05:21:00.507 回答