title: How to get the latest record based on Timestamp in SQL Server with Join
body: <p>I'm using SQL Server 2012. I have a table (LocationResults) with multiple columns. I want to get all the columns that are also present in another table (TargetAssociationDetails) - but only those rows that were inserted the newest and are also present in the second table.</p>
  
  <p>My TargetAssociationDetails table:</p>
  
  <pre><code>MSISDN        IMEI    IMSI
  --------------------------
  14085551107   NULL    NULL
  14085551108   NULL    NULL
  14085551113   NULL    NULL
  </code></pre>
  
  <p>My LocationResults table:</p>
  
  <pre><code>Latitude    Longitude       MSISDN        IMSI  IMEI    RecordedTimeStamp
  ---------------------------------------------------------------------------
  57.785125   -123.40476      14085551107   NULL  NULL    05:54.8
  57.78374111 -123.4027269    14085551107   NULL  NULL    19:12.6
  57.78476194 -123.4045131    14085551107   NULL  NULL    09:08.3
  57.61768861 -123.4081439    14085551108   NULL  NULL    19:08.4
  57.801585   -123.45619      14085551114   NULL  NULL    19:08.5
  57.55303194 -123.3019161    14085551113   NULL  NULL    19:08.5
  </code></pre>
  
  <p>This is my query - </p>
  
  <pre><code>SELECT MAX(lr.RecordTimestamp) AS RecordedTimeStamp, lr.IMEI, lr.IMSI, lr.MSISDN 
  FROM LocationResults lr LEFT OUTER JOIN TargetAssosiationDetails tad ON 
  tad.IMEI = lr.IMEI AND tad.IMSI = lr.IMSI AND tad.MSISDN = lr.MSISDN
  GROUP BY lr.IMEI, lr.IMSI,lr.MSISDN
  </code></pre>
  
  <p>But in this case, I'm not able to get all the columns. I'm only able to get those columns that I'm grouping by.</p>
  
  <p>The result I want is - </p>
  
  <pre><code>Latitude    Longitude       MSISDN        IMSI  IMEI    RecordedTimeStamp
  ---------------------------------------------------------------------------
  57.78374111 -123.4027269    14085551107   NULL  NULL    19:12.6
  57.61768861 -123.4081439    14085551108   NULL  NULL    19:08.4
  57.55303194 -123.3019161    14085551113   NULL  NULL    19:08.5
  </code></pre>
  
  <p>I'm absolutely new to DB querying so it will be great if you can post a script along with an explanation of what it does.</p>
  
  <p>Thanks in advance.</p>