Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting most recent distinct records

Considering the following table:

User  CreatedDateTime   Quantity
----- ----------------- --------
Jim   2012-09-19 01:00  1
Jim   2012-09-19 02:00  5
Jim   2012-09-19 03:00  2
Bob   2012-09-19 02:00  2
Bob   2012-09-19 03:00  9
Bob   2012-09-19 05:00  1

What query would return the most recent rows (as defined by CreatedDateTime) for each User, so that we could determine the associated Quantity.

i.e. the following records

User  CreatedDateTime   Quantity
----- ----------------- --------
Jim   2012-09-19 03:00  2
Bob   2012-09-19 05:00  1

We thought that we could simply Group By User and CreatedDateTime and add a Having MessageCreationDateTime = MAX(.MessageCreationDateTime. Of course this does not work because Quantity is not available following the Group By.

like image 767
Richard Ev Avatar asked Jan 30 '26 07:01

Richard Ev


2 Answers

Since you are using SQL Server, you can use Window Function on this.

SELECT [User], CreatedDateTime, Quantity
FROM
    (
        SELECT [User], CreatedDateTime, Quantity,
                ROW_NUMBER() OVER(PARTITION BY [User] ORDER BY CreatedDateTime DESC) as RowNum
        FROM tableName
    ) a
WHERE  a.RowNum = 1

SQLFiddle Demo

like image 112
John Woo Avatar answered Feb 01 '26 19:02

John Woo


;WITH x AS
(
  SELECT [User], CreatedDateTime, Quantity, 
   rn = ROW_NUMBER() OVER (PARTITION BY [User] ORDER BY CreatedDateTime DESC)
  FROM dbo.table_name
)
SELECT [User], CreatedDateTime, Quantity
FROM x WHERE rn = 1;
like image 28
Aaron Bertrand Avatar answered Feb 01 '26 20:02

Aaron Bertrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!