title: How to exclude rows with date range overlaps
body: <p>Postgresql - Data is in the following format</p>
  
  <p>I am currently using the following SQL to get me all the booking dates set for a property</p>
  
  <p>However, in a single day, when a user changes booking dates for a property several times then multiple entries are created which inflate the aggregate result.</p>
  
  <p>Can I apply <code>if-else</code> logic to overlapping booking_dates (highlighted in red and yellow) to pick only the booking dates with max (updated_at)(highlighted in yellow)?</p>
  
  <p>For example, red and yellow rows have overlapping booking dates. If I applied the following SQL then my sum will be incorrect. So, I only need to consider the booking dates when updated_at is max.</p>
  
  <pre><code>WITH X AS (SELECT distinct booking_end_date, booking_start_date, P_id
  FROM booking)
  SELECT sum(X.booking_end_date-X.booking_start_date) as Available, X.P_id
  from X
  group by X.P_id
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/bWWuo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bWWuo.png" alt="enter image description here"></a></p>