1

I have a PostgreSQL table like this:

table1:

MARKET        character varying 10
COST1         Number

MARKET       DATE           VALUE
A            01/01/2018      10   
A            01/02/2018      45
A            01/04/2018      12 
B            01/01/2018      12
B            01/05/2018      12
B            01/04/2018      12

I have another table like:

table2:

DATE
01/01/2018 
01/02/2018 
01/03/2018 
01/04/2018 
01/05/2018

i am trying to join these two tables such that each "MARKET" from table1 should have all the date ranges in table2. If the "DATE" is not present in table1 its corresponding "VALUE" column should be zero.

OUTPUT should be:

    MARKET       DATE           VALUE
    A            01/01/2018      10   
    A            01/02/2018      45
    A            01/03/2018      0
    A            01/04/2018      12 
    A            01/05/2018      0
    B            01/01/2018      12
    B            01/02/2018      0
    B            01/03/2018      0
    B            01/04/2018      12
    B            01/05/2018      12

Still pretty new to postgres. Any help will be appreciated!

1
  • Please remove the tags for mysql and oracle. Clearly you are not using those products. Commented Jun 8, 2018 at 19:11

1 Answer 1

3

For this type of problem, generate the rows with a cross join. The use another mechanism (left join) to bring in the values.

select m.market, t2.date, coalesce(t1.value, 0) as value
from (select distinct market from t1) m cross join
     t2 left join
     t1
     on t1.market = m.market and t1.date = t2.date;
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.