title: Calculating time when both apartments unoccupied - mysql
body: <p>I have 2 tables to report on occupancy for 2 holiday aparments.</p>
  
  <p>Columns are
  id, arrivalweek, departureweek. Simple SMALLINTs</p>
  
  <p>I already have a system where I can specify a period in the year by start week and an end week, and see how many weeks an individual apartment is occupied within that period. This works fine and is shown below, for example to see how many weeks apartment 1 was occupied between weeks 5 and 22 ...</p>
  
  <pre><code>$begin=5; // start of analysis period
  $end=22;  // end of analysis period
  
   // ###############################################################################
  // Apartment 1
  // ##################################################################################
  $totalperiod=0;$arrivalweek=0;$departureweek=0;$period=0;
  foreach($db-&gt;query('SELECT   id, arrivalweek, departureweek FROM apartment1  WHERE departureweek &gt; '.$begin.' AND arrivalweek &lt; '.$end.'  ORDER BY id ASC') as $record)
  {
  $arrivalweek=$record['arrivalweek'];  
  $departureweek=$record['departureweek']; 
  if ($arrivalweek&lt;$begin) {$arrivalweek=$begin;} // we might already be in occupancy.
  if($departureweek&gt;$end){$departureweek=$end;}   // we might not have vacated yet.
  $period=$departureweek-$arrivalweek; // period for this sector
  $totalperiod=$totalperiod+$period;  // add all sectors to get total period
  }
  echo "Time range from ".$begin." to ".$end.", for apartment 1&lt;br&gt;";
  echo $totalperiod." = total weeks occupied for apartment 1 in that period&lt;br&gt;";
  // ##################################################################################
  // End of individual apartment occupancy code
  // ##################################################################################
  </code></pre>
  
  <p>Now, I would like to be able to know how many weeks in that period BOTH apartments are unoccupied, and have struggled to find a solution. Total number of weeks when apartment 1 NOT occupied AND apartment 2 NOT occupied, over the specified time period.</p>
  
  <p>Any clues much welcomed!</p>
  
  <p>Thanks</p>
  
  <p>G</p>