title: Find min date in a range with conditions in SQL
body: <p>I need to find the first StayStart by customer within the same LegalStart/LegalEnd dates that are >= 8 days (LOS) and are Type 1 only.  Consecutive stays of Type 1 that are less than 8 days count if they add up to 8 days and there isn’t another Type interrupting them.  In that case I need the earliest of the consecutive stays. And that is what I can't figure out how to approach. Adding up consecutive stays that are under 8 but add up to 8. I’d love to post something I’ve tried, but I have gotten nowhere.<br>
  This is my table:</p>
  
  <pre><code>cust# LegalStart    StayStart   StayEnd    LegalEnd       Type  LOS(days) 
  1000    5/3/2013    2/1/2016    2/5/2016    11/18/2016        1       4
  1000    5/3/2013    2/5/2016    2/8/2016    11/18/2016        1       3
  1000    5/3/2013    2/8/2016    2/11/2016   11/18/2016        2       3
  1000    5/3/2013    2/11/2016   2/28/2016   11/18/2016        1      17
  1000    3/2/2016    3/2/2016    3/5/2016    11/18/2016        1       4
  1000    3/2/2016    3/5/2016    3/7/2016    11/18/2016        1       2
  1000    3/2/2016    3/7/2016    3/11/2016   11/18/2016        1       4
  1000    3/2/2016    3/12/2016   3/22/2016   11/18/2016        1      10
  2000    3/1/2011    12/1/2015   12/3/2015   1/8/2016          1       2
  2000    3/1/2011    12/3/2015   12/5/2015   1/8/2016          1       2
  2000    3/1/2011    12/5/2015   12/6/2015   1/8/2016          1       1
  2000    3/1/2011    12/6/2015   12/18/2015  1/8/2016          1      12
  </code></pre>
  
  <p>Expected Results  </p>
  
  <pre><code>cust#   LegalStart  StayStart   StayEnd     LegalEnd     Type   LOS(days)
  1000    5/3/2013    2/11/2016   2/28/2016   11/18/2016     1      17
  1000    3/2/2016    3/2/2016    3/5/2016    11/18/2016     1       4
  2000    3/1/2011    12/1/2015   12/3/2015   1/8/2016       1       2
  </code></pre>
  
  <p>My first result is the one with the 17 LOS because the rows for that customer previous to it do add up to 10 days HOWEVER, one of those stays is a Type 2 so it doesn’t count.  The other 2 stays add up to 7 days so they don’t count.  Therefore, the StayStart of 2/11/16 with an LOS of 17 is the min date that meets my criteria.<br>
  The second result for that same cust# is during the next Legal Date timeframe and that stay of 4 days plus the next 2 stays of 2 days and 4 days are all Type 1 so they add up to more than or = 8 days. Therefore the StayStart date of 3/2/16 is the min date that meets my criteria.<br>
  The 3rd result line is of the next customer and that is correct because all 4 rows for that customer are Type 1 and add up to >= 8 days. Therefore, the StayStart of 12/1/15 is the min date that meets my criteria.<br>
  Thanks for any help you can offer.</p>