Merging trips to the same location with overlapping dates
Let's look at this line:


(p.StartDate &lt;= startDateUnix &amp;&amp; (endDateUnix &gt;= p.StartDate &amp;&amp; endDateUnix &lt;= p.EndDate))



If p.StartDate &lt;= startDateUnix then p.StartDate &lt;= endDateUnix, since startDateUnix &lt;= endDateUnix. So endDateUnix &gt;= p.StartDate is redundant.

So the first part of the query can be written as

(p.StartDate &gt;= startDateUnix &amp;&amp; p.StartDate &lt;= endDateUnix) || 
(p.EndDate &gt;= startDateUnix &amp;&amp; p.EndDate &lt;= endDateUnix) || 
(p.StartDate &lt;= startDateUnix &amp;&amp; endDateUnix &lt;= p.EndDate)


I would recommend rewriting the first two conditions as follows:

(startDateUnix &lt;= p.StartDate &amp;&amp; p.StartDate &lt;= endDateUnix) || 
(startDateUnix &lt;= p.EndDate &amp;&amp; p.EndDate &lt;= endDateUnix)


I find it easier to see at a glance that it's saying that p.StartDate lies within [startDateUnix, endDateUnix] (similarly for p.EndDate).



Another way to test for overlapping intervals is

p.StartDate &lt;= endDateUnix &amp;&amp; startDateUnix &lt;= p.EndDate