title: SELECT MIN Date(using WINDOW function) and MAX Date(with related field using JOIN) together
body: <p>Table T1</p>
  
  <pre><code>+----+------------+------------+--------+------+
  | ID |   Sdate    |   Edate    | Reason | Type |
  +----+------------+------------+--------+------+
  |  1 | 5/30/2016  |            |        | A    |
  |  1 | 1/19/2016  | 12/15/2016 | USD    | B    |
  |  1 | 11/20/2016 | 10/1/2016  | IT     | B    |
  |  2 | 10/25/2016 |            |        | A    |
  |  2 | 9/22/2016  | 7/11/2016  | SD     | B    |
  |  2 | 2/13/2016  |            |        | A    |
  |  2 | 1/1/2016   | 4/3/2016   | IT     | B    |
  +----+------------+------------+--------+------+
  </code></pre>
  
  <p>For each ID, I need to select the minimum Sdate for Type=A and maximum Edate for Type=B, alongwith the Discharge Reason associated with Type=B. There are more than just two types but I've shown A and B as an example</p>
  
  <p><strong>Desired Output:</strong></p>
  
  <pre><code>+-------------+-----------+------------+------------------+
  | Customer ID | Startdate |  Enddate   | Discharge Reason |
  +-------------+-----------+------------+------------------+
  |           1 | 5/30/2016 | 12/15/2016 | USD              |
  |           2 | 2/13/2016 | 7/11/2016  | SD               |
  +-------------+-----------+------------+------------------+
  </code></pre>
  
  <p>Attempt:</p>
  
  <pre><code>WITH CTE AS
  (
  SELECT
      ID
      ,SDate
      ,EDate
      ,Reason
      ,Type
  FROM T1
  )
  
  SELECT
       CTE.ID AS [Customer ID]
      ,MIN(CASE WHEN CTE.Type='A' THEN CTE.SDate END)
          OVER (PARTITION BY CTE.CID) AS StartDate
      ,CTE.EDate AS Enddate
      ,CTE.Reason AS [Discharge Reason]
  
  FROM CTE
  INNER JOIN (SELECT CTE.ID, MAX(CTE.EDate) AS EEDate 
  FROM CTE WHERE CTE.Type='B' GROUP BY CTE.ID) CTE2
      ON CTE.ID=CTE2.ID AND CTE.Edate=CTE2.EEDAte
  </code></pre>
  
  <p>This gives me a blank Startdate column since the INNER JOIN on outer co-related subquery which is used to get the Max <code>Edate</code> and the associated <code>Discharge Reason</code>, causes the query to ignore <code>Type=A</code> and hence no Startdates. How do I make these work together?</p>