Someguywhocodes
Someguywhocodes

Reputation: 781

Joining data which has the same column name

Apologies for the messy title, I'm not sure what's the best way to phrase it. I have two daily tables, the first looks like this:

| yyyy_mm_dd | x_id | feature     | impl_status   |
|------------|------|-------------|---------------|
| 2020-08-18 | 1    | Basic       | first_contact |
| 2020-08-18 | 1    | Last Minute | first_contact |
| 2020-08-18 | 1    | Geo         | first_contact |
| 2020-08-18 | 2    | Basic       | implemented   |
| 2020-08-18 | 2    | Last Minute | first_contact |
| 2020-08-18 | 2    | Geo         | no_contact    |
| 2020-08-18 | 3    | Basic       | no_contact    |
| 2020-08-18 | 3    | Last Minute | no_contact    |
| 2020-08-18 | 3    | Geo         | implemented   |

While the second looks like this:

| yyyy_mm_dd | x_id | payment |
|------------|------|---------|
| 2020-08-18 | 1    | 0       |
| 2020-08-18 | 2    | 0       |
| 2020-08-18 | 3    | 1       |
| 2020-08-19 | 1    | 0       |
| 2020-08-19 | 2    | 0       |
| 2020-08-19 | 3    | 1       |

I want to build a query in which payment becomes a feature in the first table. there will be no first_contact status since payment is a boolean (1/0). This is what I've tried:

select
    yyyy_mm_dd,
    t1.x_id
    t1.impl_status
from
    schema.table1 t1
left join(
    select
        yyyy_mm_dd,
        x_id,
        'payment' as feature,
        if(payment=1, 'implemented', 'no_contact') as impl_status
    from
         schema.table2
 ) t2 on t2.yyyy_mm_dd = t1.yyyy_mm_dd and t2.x_id = t1.x_id

However doing this, I will need to select either t1.impl_status or t2.impl_status due to ambiguity. The two columns are not combined.

With this in mind, the expected output would look like this:

| yyyy_mm_dd | x_id | feature     | impl_status   |
|------------|------|-------------|---------------|
| 2020-08-18 | 1    | Basic       | first_contact |
| 2020-08-18 | 1    | Last Minute | first_contact |
| 2020-08-18 | 1    | Geo         | first_contact |
| 2020-08-18 | 1    | Payment     | no_contact    |
| 2020-08-18 | 2    | Basic       | implemented   |
| 2020-08-18 | 2    | Last Minute | first_contact |
| 2020-08-18 | 2    | Geo         | no_contact    |
| 2020-08-18 | 2    | Payment     | no_contact    |
| 2020-08-18 | 3    | Basic       | no_contact    |
| 2020-08-18 | 3    | Last Minute | no_contact    |
| 2020-08-18 | 3    | Geo         | implemented   |
| 2020-08-18 | 3    | Payment     | implemented   |
| 2020-08-19 ...
 ...

Upvotes: 1

Views: 33

Answers (1)

GMB
GMB

Reputation: 222652

You can use union all:

select yyyy_mm_dd, x_id, feature, impl_status from table1 t1
union all
select yyyy_mm_dd, x_id, 'Payment', case when payment = 0 then 'no_contact' else 'implemented' end from table2

Upvotes: 1

Related Questions