Edu Galindo
Edu Galindo

Reputation: 165

copyng values from one column to another sql

I have a list like this:

| slope | lower_limit | upper_limit | limit |
|-------|-------------|-------------|-------|
|  -0.5 |          23 |          25 |     0 |
|   0.6 |          23 |          25 |     0 |
|   0.7 |          23 |          25 |     0 |

I want to update values of the limit column from the lower limit and upper limit columns, depending of the sign of the slope column. I would like the resulting table to look like this:

| slope | lower_limit | upper_limit | limit |
|-------|-------------|-------------|-------|
|  -0.5 |          23 |          25 |    23 |
|   0.6 |          23 |          25 |    25 |
|   0.7 |          23 |          25 |    25 |

I am currently using an if, but it changes the value of the whole column, resulting in all values in the limit column being 25

Upvotes: 1

Views: 48

Answers (1)

D-Shih
D-Shih

Reputation: 46219

I think you can try to use CASE WHEN in update.

CREATE TABLE T(
   slope FLOAT, 
  lower_limit INT, 
  upper_limit  INT,
  limit INT
);

INSERT INTO T  VALUES (-0.5,23,25,0);
INSERT INTO T  VALUES (0.6,23,25,0); 
INSERT INTO T  VALUES (0.7,23,25,0);


UPDATE T
SET limit = CASE WHEN slope > 0 THEN upper_limit 
                    ELSE lower_limit  END  

Query 1:

select * from t

Results:

| slope | lower_limit | upper_limit | limit |
|-------|-------------|-------------|-------|
|  -0.5 |          23 |          25 |    23 |
|   0.6 |          23 |          25 |    25 |
|   0.7 |          23 |          25 |    25 |

Upvotes: 4

Related Questions