Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

How to update multiple columns in same update statement with one column depends upon another new column new value in Redshift

I want to update multiple columns in same update statement with one column depends upon another new column new value.

Example:

Sample Data: col1 and col2 is the column names and test_update is the table name.

SELECT * FROM test_update;
col1    col2
col-1   col-2
col-1   col-2
col-1   col-2

update test_update set col1 = 'new', col2=col1||'-new';

SELECT * FROM test_update;
col1    col2
new col-1-new
new col-1-new
new col-1-new

What I need to achieve is col2 is updated as new-new as we updated value of col1 is new.

I think may be its not possible in one SQL statement. If possible How can we do that, If its not What is best way of handling this problem in Data Warehouse environment, like execute multiple update 1st on col1 and then on col2 or any other.

Hoping my question is clear.

question from:https://stackoverflow.com/questions/65559570/how-to-update-multiple-columns-in-same-update-statement-with-one-column-depends

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot update the second column based on the result of updating the first column. However this can be achieved in a single by "pre-calculating" the result you want and then updating based on that.

The following update using a join is based on the example provided in the Redshift documentation:

UPDATE test_update 
SET col1 = precalc.col1
  , col2 = precalc.col2
FROM (
    SELECT catid
         , 'new' AS col1
         , col1 || '-new' AS col2
    FROM test_update
    ) precalc
WHERE test_update.id = precalc.id;
;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...