Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a SQL query to retrieve most recent records

I am creating a status board module for my project team. The status board allows the user to to set their status as in or out and they can also provide a note. I was planning on storing all the information in a single table ... and example of the data follows:

Date               User         Status    Notes ------------------------------------------------------- 1/8/2009 12:00pm   B.Sisko      In        Out to lunch     1/8/2009 8:00am    B.Sisko      In   1/7/2009 5:00pm    B.Sisko      In     1/7/2009 8:00am    B.Sisko      In     1/7/2009 8:00am    K.Janeway    In    1/5/2009 8:00am    K.Janeway    In     1/1/2009 8:00am    J.Picard     Out       Vacation   

I would like to query the data and return the most recent status for each user, in this case, my query would return the following results:

Date               User         Status    Notes -------------------------------------------------------   1/8/2009 12:00pm   B.Sisko      In        Out to lunch     1/7/2009 8:00am    K.Janeway    In    1/1/2009 8:00am    J.Picard     Out       Vacation   

I am try to figure out the TRANSACT-SQL to make this happen? Any help would be appreciated.

like image 447
mattruma Avatar asked Jun 26 '09 15:06

mattruma


People also ask

How do I find most recent records in SQL?

Here is the syntax that we can use to get the latest date records in SQL Server. Select column_name, .. From table_name Order By date_column Desc; Now, let's use the given syntax to select the last 10 records from our sample table.

How do I select the recently updated records from the table in SQL?

To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.

How do I get last 10 records in SQL?

Let us now implement the above query. mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records. We can match both records with the help of the SELECT statement.

How do I get last 7 days record in SQL?

We use system function now() to get the latest datetime value, and INTERVAL clause to calculate a date 7 days in the past.


1 Answers

Aggregate in a subquery derived table and then join to it.

 Select Date, User, Status, Notes      from [SOMETABLE]     inner join      (         Select max(Date) as LatestDate, [User]         from [SOMETABLE]         Group by User     ) SubMax      on [SOMETABLE].Date = SubMax.LatestDate     and [SOMETABLE].User = SubMax.User  
like image 86
cmsjr Avatar answered Oct 05 '22 23:10

cmsjr