title: Conditional Inner Join
body: <p>I want to be able to inner join two tables based on the result of an expression.</p>
  
  <p><strong>What I've been trying so far:</strong></p>
  
  <pre><code>INNER JOIN CASE WHEN RegT.Type = 1 THEN TimeRegistration ELSE DrivingRegistration AS RReg
  ON
  RReg.RegistreringsId = R.Id
  </code></pre>
  
  <p>RegT is a join I made just before this join:</p>
  
  <pre><code>INNER JOIN RegistrationTypes AS RegT ON R.RegistrationTypeId = RegT.Id
  </code></pre>
  
  <p>This SQL-script does not work.</p>
  
  <p>So all in all, if the <code>Type</code> is 1, then it should join on the table <code>TimeRegistration</code> else it should join on <code>DrivingRegistration</code>.</p>
  
  <p><strong>Solution:</strong></p>
  
  <p>In my select statement I performed the following joins:</p>
  
  <pre><code>INNER JOIN  RegistrationTypes AS RegT ON R.RegistrationTypeId = RegT.Id
  LEFT OUTER JOIN TimeRegistration AS TReg ON TReg.RegistreringsId = R.Id AND RegT.Type = 1
  LEFT OUTER JOIN DrivingRegistration AS DReg ON DReg.RegistreringsId = R.Id AND RegT.Type &lt;&gt;1
  </code></pre>
  
  <p>Then I edited my <code>where-clause</code> to output the correct, depending on the <code>RegType</code>, like this:</p>
  
  <pre><code>WHERE (CASE RegT.Type WHEN 1 THEN TReg.RegistreringsId ELSE DReg.RegistreringsId END = R.Id)
  </code></pre>