Short Port
Short Port

Reputation: 77

Union two tables and rename table specific columns

I combine the tables:

PkID | HouseFk | house_extra_id | Price | discount_id
1    | 5       | 6              | 1205  | 0

PkID | HouseFk | PacketFk | Price | discount_id
1    | 6       | 7        | 500   | 0

using union all like so:

select  pkid,housefk,house_extra_id,price,discount_id,null as packetfk
from T1

union all

select pkid,housefk,null as house_extra_id,price,discount_id,packetfk
from t2

result is:

PkID | HouseFk | house_extra_id | Price | discount_id | PacketFk
1    | 5       | 6              | 1205  | 0           | NULL
1    | 6       | NULL           | 500   | 0           | 7

But what if I want two separate "Price" columns depending from which table it was combined? So that in the end my table looks like:

PkID | HouseFk | house_extra_id | t1_Price | t2_Price | discount_id | PacketFk
1    | 5       | 6              | 1205     | NULL     | 0           | NULL
1    | 6       | NULL           | NULL     | 500      | 0           | 7

Upvotes: 2

Views: 92

Answers (1)

Giorgos Betsos
Giorgos Betsos

Reputation: 72205

You can use even more columns, like:

select  pkid, housefk, house_extra_id, 
        price AS t1_Price, NULL AS t2_Price,
        discount_id, null as packetfk
from T1

union all

select pkid, housefk, null as house_extra_id,
       NULL AS t1_Price, price AS t2_Price,
       discount_id, packetfk
from t2

Upvotes: 5

Related Questions