Get only latest row, grouped by a column

后端 未结 5 1501
醉酒成梦
醉酒成梦 2021-01-23 03:27

I have a large data-set of emails sent and status-codes.

ID Recipient           Date       Status
 1 someone@example.com 01/01/2010      1
 2 someone@example.com         


        
5条回答
  •  青春惊慌失措
    2021-01-23 03:58

    You can use the ranking functions for this. Something like (not tested):

    WITH MyResults AS
    (
       SELECT Recipient, Status, ROW_NUMBER() OVER( Recipient ORDER BY (  [date] DESC ) ) AS   [row_number]
       FROM Messages
    )
    SELECT MyResults.Recipient, MyCounts.EmailCount, MyResults.Status
    FROM (
        SELECT Recipient, Count(*) EmailCount
        FROM Messages
        GROUP BY Recipient
    ) MyCounts
    INNER JOIN MyResults
    ON MyCounts.Recipient = MyResults.Recipient
    WHERE MyResults.[row_number] = 1
    

提交回复
热议问题