Search code examples
snowflake-cloud-data-platform

SQL Joining on column with unique values in left and right tables


I am stuck on a join, and I think I am not using the right type of join.

I have table1:

ID Time Action
1 1/1/23 08:00 Rate Verify
1 1/1/23 09:00 Rate Verify
1 1/1/23 12:00 Rate Verify
1 1/1/23 16:00 Rate Change

and table2:

ID Time Total Downloaded
1 1/1/23 08:00 10
1 1/1/23 09:00 20
1 1/1/23 11:00 40
1 1/1/23 17:00 95

and want to join the tables like so:

ID Time Action Total Downloaded
1 1/1/23 08:00 Rate Verify 10
1 1/1/23 09:00 Rate Verify 20
1 1/1/23 11:00 null 40
1 1/1/23 12:00 Rate Verify null
1 1/1/23 16:00 Rate Change null
1 1/1/23 17:00 null 95

I have tried:

from table1
left join table2 on (table1.id=table2.id) and     (table1.time=table2.time or table1.time is null or      table2.time is null)

This however excludes times from table2 that do not exist in table1

Thank you in advance for your advice


Solution

  • I think you're looking for a FULL OUTER JOIN:

    with table1 as (
    select *
    from (values(1,'1/1/23 08:00','Rate Verify'),
                (1,'1/1/23 09:00','Rate Verify'),
                (1,'1/1/23 12:00','Rate Verify'),
                (1,'1/1/23 16:00','Rate Change'))x(id,time,action)
    ), table2 as (
    select *
    from (values(1,'1/1/23 08:00',10),
                (1,'1/1/23 09:00',20),
                (1,'1/1/23 11:00',40),
                (1,'1/1/23 17:00',9))x(id,time,total_download)
    )
    select coalesce(t1.id,t2.id) as id,
           coalesce(t1.time,t2.time) as time,
           t1.action,
           t2.total_download
    from table1 t1
    full outer join table2 t2
    on t1.id = t2.id
    and t1.time = t2.time
    order by time;