0

There is a data_table with four columns. I am trying to make up a SELECT statement that transforms each initial row into one or two rows depending on a value in type column.

For example, when type = 'X' row (a,b,c) is transformed into (a,b) and (a,c), otherwise it is just (a,b).

initial_data_table

|  a   |  b  |  c  |  type
---------------------------
|  1   |  2  |  3  |   X  
|  4   |  5  |  6  |   Y
---------------------------

query result

|  first   | second |  type
---------------------------
|    1     |   2    |   X  
|    1     |   3    |   X  
|    4     |   5    |   Y
---------------------------

Could you help me tow find out how to "split" rows on condition in a relational way using only SQL?

1 Answer 1

1

I am thinking a lateral join with some filtering:

select v.*
from t cross join lateral
     (values (a, b, type),
             (a, c, nullif(type, 'Y'))
     ) v(first, second, type)
where type is not null;

However union all would work well too:

select a, b, type
from t
union all
select a, b, type
from t
where type = 'X';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.