Solved

Sql query to last records from table

Posted on 2016-10-05
3
66 Views
Last Modified: 2016-10-08
I have sql table with these columns
CrewID
Lat
Lon
DateCreated

Now this table stores Latitude and Longitude of each crew when he travels along with Datetime when the position is recorded.

I need to write a query which will give me the last recorded position of each crew from this table bases on DateCreated.
0
Comment
Question by:yadavdep
3 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 500 total points
ID: 41830134
<Knee jerk reaction.  Write a subquery to get the most recent DateCreated for each CrewID, then join on the table as a main query.  Change YourTable and aliases to meet your needs. > 

SELECT yt.CrewID, yt.Lat, yt.Lon, yt.DateCreated
FROM YourTable yt
   JOIN (
      SELECT CrewID, Max(DateCreated) as DateCreatedMax
      FROM YourTable
      GROUP BY CrewID) ytmax ON yt.CrewID = ytmax.CrewID AND yt.DateCreated = ytmax.DateCreatedMax
ORDER BY yt.CrewID

Open in new window

0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 41830605
SELECT CrewID, Lat, Lon, DateCreated
FROM (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY CrewID ORDER BY DateCreated DESC) AS row_num
    FROM table_name
) AS derived
WHERE row_num = 1
0
 
LVL 28

Expert Comment

by:Pawan Kumar
ID: 41830978
SELECT x.CrewID, x.Lat, x.Lon, n.DateCreated
FROM YourTable x
CROSS APPLY
(
        SELECT MAX(y.DateCreated) DateCreated
	FROM YourTable y
	WHERE x.CrewID = y.CrewID    
)n

Open in new window

0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

PL/SQL can be a very powerful tool for working directly with database tables. Being able to loop will allow you to perform more complex operations, but can be a little tricky to write correctly. This article will provide examples of basic loops alon…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question