Skip to content
Advertisement

Creating a new column using the result set from union all – sql

I have TWO simple VIEWS with columns PID and NAME respectively. Here’s how they are connected to each other.

View1:

PID NAME

Comp1 , C1

Comp2 , C2

View2:

PID NAME ParentPID

Pool1 , P1 , Comp1

Pool2 , P2 , Comp2

I want to create a view with below columns by using UNION ALL statement (I guess that’s the easiest approach)

PID , NAME , PID:NAME

Comp1 , C1 , C1

Comp2 , C2 , C2

Pool1 , P1 , C1:P1

Pool2 , P2 , C2:P2

If I just use PID and NAME columns, the union all statement would work correctly. for example:

But it fails when I tried to create a new column using UNION ALL as shown below.

Advertisement

Answer

The two queries in a UNION ALL are independent of each other. You can’t reference one inside the other. It looks like what you want is:

So in the second query, you need to join view1 and view2:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement