Let's assume this is my current data:
product_number date value
100 2010-01-01 1
100 2010-02-01 1
100 2010-03-01 1
200 2010-01-01 1
200 2010-03-01 1
How can I join the table on "itself", to fill the dates where other products have missing dates (compared to all the results, that change all the time)?
As you can see, product #200 doesn't have a 2010-02-01 date and I need to get a NULL value there.
Expected result:
product_number date value
100 2010-01-01 1
100 2010-02-01 1
100 2010-03-01 1
200 2010-01-01 1
200 2010-02-01 NULL # add NULL values where it doesn't have a date
200 2010-03-01 1
Basically: get a list of all distinct dates, find products where that date doesn't exist and simulate an entry with a NULL or empty value to fill the gap
Best Answer
You'll need to first create a list of every
product_number
anddate
combination. You can do this using aCROSS JOIN
of your table:See SQL Fiddle with Demo. This will create a list of data similar to:
You will then use the above query and
LEFT JOIN
to your table to return the final result:See SQL Fiddle with Demo. Giving a final result of:
The
LEFT JOIN
returns all rows from your list of products and dates regardless of whether a matching row exists in the other table.This could also be written as:
See SQL Fiddle with Demo. This may have better performance depending on your table size.
Now if you wanted to return a list of all dates, regardless of whether or not they appear in the table, then I would suggest creating a table of dates. This table would be used in a similar manner to create a list of all dates/products which you would then join.
The table would be similar to:
You'd then use the following query to get the list of dates/products:
And finally, you would join that back to your table:
See SQL Fiddle with Demo. Or an alternative:
See SQL Fiddle with Demo. Again this may have better performance based on the table size. Using this type of solution, you'd return all dates even those not in your table: