Home > Software design >  PostgreSQL: How to modify values in view
PostgreSQL: How to modify values in view

Time:09-22

I have a table I don't want to touch, but from this table I want to create many views that will serve different purposes/analyses.

In one case, I need to change a value based on a condition (-1 become some positive value).

Is it even possible to do that in PostgreSQL?

For example, -1 in the table will become 1 in the view if Col3='B':

 ------ ------ ------      ------ ------ ------ 
| Col1 | Col2 | Col3 |    | Col1 | Col2 | Col3 |
 ------ ------ ------  >   ------ ------ ------ 
|    1 |  3.5 | A    | >  |    1 |  3.5 | A    |
|    2 |   -1 | B    | >  |    2 |    1 | B    |
|    3 |   -1 | A    |    |    3 |   -1 | A    |
 ------ ------ ------      ------ ------ ------ 

CodePudding user response:

You need to modify the view an put the logic in the query:

select col1,
       (case when col3 = 'B' and col2 = -1 then 1 else col2 end) as col2,
       col3
from . . .
  • Related