?
Solved

Sql query to last records from table

Posted on 2016-10-05
3
Medium Priority
?
88 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 66

Accepted Solution

by:
Jim Horn earned 2000 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 70

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 37

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

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Question has a verified solution.

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

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.
Suggested Courses

850 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