简体   繁体   English

如何在Teradata中使用ROW_NUMBER()更新列?

[英]How to UPDATE column with ROW_NUMBER() in Teradata?

I'm having a table like this 我有这样的桌子

Create table test1(emp_id decimal(5,0), emp_name varchar(20));

Insert into test1(2015,'XYZ');
Insert into test1(2016,'XYZ2');

Now I want to update emp_id to row_number() or add new column into same table like (emp_no integer) to row_number(). 现在,我想将emp_id更新为row_number()或将新列添加到同一表中,例如将(emp_no integer)添加到row_number()。

can anyone please tell me the query for this? 谁能告诉我这个查询吗?

You need to use UPDATE FROM: 您需要使用UPDATE FROM:

UPDATE test1
FROM
 ( SELECT ROW_NUMBER() OVER (ORDER BY emp_id) AS rn,
     emp_id 
   FROM test1
 ) AS src
SET emp_id = src.rn
WHERE test1.emp_id = src.emp_id -- must be unique column(s)

Btw, instead of updating all rows of a table it might be better to INSERT/SELECT or MERGE the SELECT into a new table. 顺便说一句,与其更新表的所有行,不如将INSERT / SELECT或SELECT合并到新表中可能更好。 You must do it if there's no unique column, you should if emp_id is the PI of your table (otherwise performance will be horrible). 如果没有唯一列,你必须做到这一点,你应该如果emp_id是你的表的PI(否则性能会可怕)。

Create table test1(
  emp_id decimal(5,0), 
  emp_name varchar(20),
  emp_no INTEGER GENERATED ALWAYS AS IDENTITY
         (START WITH 1
          INCREMENT BY 1
         )
);

Insert into test1(2015,'XYZ1',2);
Insert into test1(2016,'XYZ2',2);      
Insert into test1(2015,'XYZ3',null);
Insert into test1(2016,'XYZ4',null);      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM