wilko100
asked on
SQL get latest date from records
Hi
I have a single table that has a one to many relationship and i want the get the top, latest date from those records used.
So for example the following records have IDs and against each ID can have multiple records:
ID Date
1 01/09/2013
1 02/09/2013
1 03/09/2013
2 06/09/2013
2 07/07/2013
2 08/07/2013
2 09/07/2013
I want to return one single record per ID, in this case id 1 and 2 with the latest date
i.e would return.
ID Date
1 03/09/2013
2 09/09/2013
I have a single table that has a one to many relationship and i want the get the top, latest date from those records used.
So for example the following records have IDs and against each ID can have multiple records:
ID Date
1 01/09/2013
1 02/09/2013
1 03/09/2013
2 06/09/2013
2 07/07/2013
2 08/07/2013
2 09/07/2013
I want to return one single record per ID, in this case id 1 and 2 with the latest date
i.e would return.
ID Date
1 03/09/2013
2 09/09/2013
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
With CTE and join is not necessary, just -
SELECT ID, Date, columnA, columnB, ... FROM
(SELECT ID, Date, columnA, columnB, ...,
ROW_NUMBER() OVER (PARTITION BY ID, ORDER BY Date DESC) AS rn
FROM manyTable) as x
)
WHERE rn = 1;
SELECT ID, Date, columnA, columnB, ... FROM
(SELECT ID, Date, columnA, columnB, ...,
ROW_NUMBER() OVER (PARTITION BY ID, ORDER BY Date DESC) AS rn
FROM manyTable) as x
)
WHERE rn = 1;
lol it's the exact same thing cte just makes it easier to read.
ASKER
Excellent, nice and simple solution, works great thanks
Thanks for the grade. Good luck with your project. -Jim
WITH cte (ID, Date, columnA, columnB, ..., RowNumber)
AS
(
SELECT ID, Date, columnA, columnB, ...,
ROW_NUMBER() OVER (PARTITION BY ID, ORDER BY Date DESC) AS RowNumber
FROM manyTable
)
SELECT T1.ID, cte.Date, cte.columnA, cte.ColumnB, ...
FROM oneTable AS T1
INNER JOIN cte
ON T1.ID = cte.ID
AND cte.RowNumber = 1