title: SQL JOIN two tables based on periods
body: <p>I have two tables one has weeks and their start and end date. Second contains months with start and end dates.
  I want them to be joined like on the picture.</p>
  <p><img src="https://i.stack.imgur.com/McwZI.png" alt="way how joined table should looks like" /><br></p>
  <p>I tried to use CASE WHEN in WHERE clause to achieve what I want but still have some troubles:<br>
  Here is my query:<br></p>
  <pre><code>SELECT * FROM TAB_A AS ref
  INNER JOIN TAB_B AS in
  ON ref.cal_id = in.cal_id
  and (CASE WHEN
  ((MONTH(ref.end_date) &gt; MONTH(in.start_date)) and (MONTH(ref.start_date) != MONTH(in.start_date)) and (MONTH(ref.end_date) = MONTH(in.end_date))) 
  THEN (ref.end_date BETWEEN in.start_date AND in.end_date) 
  ELSE (ref.start_date BETWEEN in.start_date AND in.end_date)
  END)
  </code></pre>
  <p>And here is what I got from that query:</p>
  <p><img src="https://i.stack.imgur.com/52tma.png" alt="output of the query" /></p>
  <p>With 2021W48 should be 2021M12 (not like my example 2021M11)<br></p>
  <p>I tried different ways. Can you guys help me how to join those tables?</p>
  <p>Regards,<br>
  Michal</p>