title: The multi-part identifier could not be bound on Temp Table Join
body: <p>I know it's been asked many times before, however I seem to have run into an odd problem.</p>
  
  <p>I'm trying to collect data to display in a graph about the sum of money owed per month per cargo.</p>
  
  <p>I'm trying to join my query onto a temp table of months, so even if there is no data for that month, I will still get a value of 0 for the graph.</p>
  
  <p>my code:</p>
  
  <pre><code>INSERT INTO #DemurrageValuesExport
          SELECT #Months.Month,
                          SUM(CASE
                              WHEN ISNULL(PD.PotentialDemurrageCost,0) &lt; 0
                              THEN 0
                              ELSE ISNULL(PD.PotentialDemurrageCost,0)
                          END) AS [Potential Demurrage]
          FROM        dbo.Trip
                      RIGHT JOIN dbo.TripCargo
                          ON dbo.Trip.ID = dbo.TripCargo.TripID 
                      RIGHT JOIN dbo.Cargo
                          ON dbo.TripCargo.CargoID = dbo.Cargo.ID
                      LEFT JOIN #Months
                          ON Month = PD.Berthed
                      LEFT JOIN dbo.PotentialDemurrageEvents AS PD
                          ON dbo.Trip.ID = PD.TripID
                          AND PD.Berthed BETWEEN @MonthStartDate AND @MonthEndDate
                          AND dbo.TripCargo.ID = PD.TripCargoID
          WHERE dbo.Cargo.ID = @CargoID AND TripCargo.Export = 1
          GROUP BY    Month
  </code></pre>
  
  <p>This loops through each of the previous 12 months, getting values for a particular cargo.</p>
  
  <p>The problem arises on; <code>ON Month = PD.Berthed</code></p>
  
  <p>It is claiming that <code>PD.Berthed</code> could not be bound. However, I've used the alias in other places in the query and they are not causing issues. If I remove the temp table join, the query executes fine.</p>
  
  <p>Does anyone have a clue what's going on? Or failing that, achieve what I'm trying to do without joining onto another table of months at all?</p>
  
  <p>Thanks</p>