Home > database >  How to create a materialized view in SQL where a symbol is added based on the value of another colum
How to create a materialized view in SQL where a symbol is added based on the value of another colum

Time:11-22

I have a table like this:

Column A Column B
A -1
B 4
C -10
D -68
E 51
F 2

I have to create a materialized view in SQL with a new varchar column containing the column B value with a symbol added when the value is positive. I want a result like:

Column A Column B Column C
A -1 -1
B 4 4
C -10 -10
D -68 -68
E 51 51
F 2 2

I tried the following but this adds a symbol before all values:

CREATE MATERIALIZED VIEW schema.view
as
    select column a, column b, CONCAT(' ', column b)  AS column c 
    from schema.table;

CodePudding user response:

You can use a CASE statement to add the positive sign only if there isn't already a negative sign. Something like:

CREATE MATERIALIZED VIEW schema.view
as
    select columna, columnb, CASE WHEN columnb NOT LIKE '-%' THEN CONCAT(' ', columnb) ELSE columnb END columnc 
    from schema.table;

However, I would suggest revisiting whether this is actually necessary for your actual scenario. This seems like something trivial to calculate on the fly. Typically I would expect a materialized view to be used when the calculations are complex and there are performance gains that justify the duplication and wasted space. Maybe you could use a regular view or a generated column instead.

  • Related