title: Select last item for each unique column value
body: <p>I have a table containing message logs. Each conversation has a conversation ID. </p>
  
  <p>I want to select distinct conversation IDs, and for each of them, find the latest message with that conversation ID and join it into the row.</p>
  
  <p>This is what I tried but it doesn't add any data into the table except the two columns (<code>conversationId</code> and <code>id</code>). I want to get all columns from that table for each row with the latest </p>
  
  <pre><code>SELECT 
    logs.conversationId, 
    -- latest message id
    MAX(logs.id) AS id
    FROM [dbo].[Logs] AS logs
  
    -- trying to get the remaining columns for the last message with that conversation ID
    LEFT JOIN [dbo].[Logs] AS logs2 ON logs.id = logs2.id
  
    WHERE 
      -- only conversations for last month
      logs.timestamp &gt;= DATEADD(month, -1, GETDATE())
  
    GROUP BY logs.conversationId
  </code></pre>
  
  <p>When I try to add another column into <code>SELECT</code>, I get the error saying I need to add that column into the <code>GROUP BY</code> clause. But that causes the statement to run for an extremely long time, over 20 seconds for just a few dozen rows in the result.</p>