title: Overlap SQL with group by
body: <p>I have a question regarding overlap in SQL, I have the following structure and data from my database:</p>
  
  <pre><code>Table A (Id = uniqueidentifier)
  | Name |  StartDate  |    EndDate    | DaysToReceive |
  ------------------------------------------------------
  |   A  |  2019-08-26 |   2020-04-13  | 232           |
  |   A  |  2019-12-15 |   2020-04-11  | 119           |
  |   A  |  2020-03-06 |   2020-03-31  | 26            |
  |   B  |  2020-01-07 |   2020-01-31  | 25            |
  |   B  |  2020-02-11 |   2020-02-29  | 19            |
  
  </code></pre>
  
  <p>I need to get the days to receive, but if there is an overlap I need the difference between the min date and the max date otherwise I use the <code>DaysToReceive</code> Summed Column.</p>
  
  <p>I'm trying to get the result to look like this:</p>
  
  <pre><code>| Name | DaysToReceive |
  ------------------------
     A   |     232
     B   |     44
  </code></pre>
  
  <p>I have managed to get this query but only works for overlap days.</p>
  
  <pre><code>select DATEDIFF(d, MIN(t1.dt),MAX(t1.enddt)) + 1 as DaysToReceive
  from (
      select distinct cp1.dt, min(cp2.dt) enddt
      from ( select StartDate as dt, Id from TableA ) cp1, 
           ( select EndDate as dt from TableA ) cp2
      where cp2.dt &gt; cp1.dt cp1.Id = cp2.Id
      group by cp1.dt
      ) t1, TableA t2
  where t2.StartDate between t1.dt and t1.enddt
  group by t1.dt, t1.enddt
  </code></pre>
  
  <p>Thanks in advance.
  Cheers</p>