Let’s say I have a table with the following data.
- Table name [Data].
- PrimaryID: The primary id of the table.
- ParentID: The table references itself; this is a FK constraint to PrimaryID.
-
DateTime: The time that this was last updated.
PrimaryID ParentID Date 1 null 1/1/2013 2 1 1/2/2013 3 1 1/3/2013 4 null 1/4/2013 5 4 1/5/2013 6 null 1/6/2013
I want to select results that look like this:
PrimaryID ParentID
3 1
5 4
6 6
For each “group” (defined as all the entries with the same ParentID and that parent), I want to select the row that is the most recent, and also replace a null ParentID (which usually indicates that this row is the parent) with the row’s own PrimaryID.
I’m really lost on where to even begin generating a query like this.
I have an inner select that looks something like this:
(SELECT PrimaryID, ISNULL(ParentID, PrimaryID) as ParentID, Date FROM [Data])
This looks like it’s the right direction to start, but I don’t know where to go from here.
With the help of @ypercube, something like this should work:
And here is the updated Fiddle.