title: Caller whose first and last call was to the same person
body: <p>I have a phonelog table that has information about callers' call history. I'd like to find out callers whose first and last call was to the same person on a given day.</p>
  
  <pre><code>Callerid  Recipientid        DateCalled
  1          2            2019-01-01 09:00:00.000
  1          3            2019-01-01 17:00:00.000
  1          4            2019-01-01 23:00:00.000
  2          5            2019-07-05 09:00:00.000
  2          5            2019-07-05 17:00:00.000
  2          3            2019-07-05 23:00:00.000
  2          5            2019-07-06 17:00:00.000
  2          3            2019-08-01 09:00:00.000
  2          3            2019-08-01 17:00:00.000
  2          4            2019-08-02 09:00:00.000
  2          5            2019-08-02 10:00:00.000
  2          4            2019-08-02 11:00:00.000
  
  Expected Output
  Callerid   Recipientid     Datecalled
  2             5            2019-07-05
  2             3            2019-08-01
  2             4            2019-08-02
  </code></pre>
  
  <p>I wrote the below query but can't get it to return recipientid. Any help on this will be appreciated!</p>
  
  <pre><code>select pl.callerid,cast(pl.datecalled as date) as datecalled
  from phonelog pl inner join (select callerid, cast(datecalled as date) as datecalled, 
                               min(datecalled) as firstcall, max(datecalled) as lastcall
                               from phonelog
                               group by callerid, cast(datecalled as date)) as x
  on pl.callerid = x.callerid and cast(pl.datecalled as date) = x.datecalled
  and (pl.datecalled = x.firstcall or pl.datecalled = x.lastcall)
  group by pl.callerid, cast(pl.datecalled as date) 
  having count(distinct recipientid) = 1
  </code></pre>