I'm trying to use LEFT JOIN
with a condition on the right table and I'm getting a lot problems doing so.
I have two tables:
projects{project_id,start_date}
projectForeCast{project_id,year_number,month_number,hours}
I'm trying to get all projects that opened in the last week and the hours that wererecorded in the last month.
SELECT dbo.Project.PROJECT_ID, dbo.ProjectForeCast.HOURS AS F0
FROM dbo.Project LEFT JOIN dbo.ProjectForeCast ON dbo.Project.PROJECT_ID = dbo.ProjectForeCast.PROJECT_ID
WHERE (dbo.ProjectForeCast.YEAR_NUMBER = DATEPART(YYYY, DATEADD(MM, 0, DATEADD(WK, - 1, GETDATE())))) AND
(dbo.ProjectForeCast.MONTH_NUMBER = DATEPART(MM, DATEADD(MM, 0, DATEADD(WK, - 1, GETDATE())))) AND
(DATEPART(WK,dbo.Project.START_DATE) = DATEPART(WK, DATEADD(WK, - 1, GETDATE())))AND
(DATEPART(YYYY,dbo.Project.START_DATE) = DATEPART(YYYY, DATEADD(WK, - 1, GETDATE())))
It's working just fine but if the project don't have a record in projectForeCast
in the last month_number
I don't get the project at all. I want to get an empty cell or null in the column F0
in this case. This is the reason I tried the LEFT JOIN
but it didn't work.