Link to home
Start Free TrialLog in
Avatar of yadavdep
yadavdepFlag for India

asked on

Sql query to last records from table

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.
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
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