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.
Since you are using SQL Server, you can use Window Function on this.
SQLFiddle Demo