Skip to content
Advertisement

Join two table by dates and populate the missing data when one table has missing dates

In SQL Server, I have a two tables (tbl1 and tbl2) as shown below. tbl2 contains a list of all dates. In tbl1, some of the dates are missing.

tbl1

tbl2

What I need is the table below. I need to join the two table, populate the name and nameid for the missing dates, and set those counts as 0.

I did the following:

and got this output:

It does not seem to be right. Does anyone know how I can generate the desired joined table?

Below is the code to generate tbl1 and tbl2

Advertisement

Answer

To achieve your desired result, you need to cross join the distinct name values from tbl1 with the dates from tbl2 and then LEFT JOIN that to tbl1 again, using COALESCE to replace NULL values of count with 0:

Output:

Demo on dbfiddle

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement