Brian Salta
Brian Salta

Reputation: 1576

SQL Join two tables

Right now I have a table that may or may not have data for a specific day. However, I would like to return a dataset with all dates and blank data filled in for the other columns. I figured another table with "all dates" stored in it and a view would help me accomplish this. If there is a better way please let me know.

table1

UserId    Date       Value1
1         9/2/2012   10
2         9/15/2012  5
1         9/17/2012  12
1         9/23/2012  4
2         9/25/2012  7

AllDates (has a record of every date for the next 10 years)

Date
1/1/2012
1/2/2012
1/3/2012
...
...
...
12/31/2020

I would like to join the two tables to return this dataset for the month of September where UserId = 1:

UserId    Date       Value1
1         9/1/2012   NULL
1         9/2/2012   10
1         9/3/2012   NULL
...
...
...
1         9/16/2012   NULL
1         9/17/2012   12
1         9/18/2012   NULL
...
...
...
1         9/23/2012  4
...
...
...
1         9/29/2012  NULL
1         9/30/2012  NULL

Upvotes: 0

Views: 216

Answers (1)

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171371

select a.Date, t.Value1
from AllDates a
left outer join table1 t on a.Date = t.Date and t.UserID = 1
where year(a.Date) = 2012 and month(a.Date) = 9    
order by a.Date

Upvotes: 3

Related Questions