You can try this. It might work for you but without more test data it's difficult to be sure.
DECLARE @TableA TABLE (ItemID INT, Date DATETIME)
DECLARE @TableB TABLE (ItemID INT, ParentID INT)
INSERT INTO @TableA
SELECT 1, '2012-09-08' UNION ALL SELECT 2, '2012-08-07'
UNION ALL SELECT 3, '2012-09-09' UNION ALL SELECT 4, '2012-09-10'
UNION ALL SELECT 5, '2012-08-23'
INSERT INTO @TableB
SELECT 1, 2 UNION ALL SELECT 3, 2
;WITH CTE AS (
SELECT b.ItemID, b.ParentID, a.Date
FROM @TableB b
INNER JOIN @TableA a ON b.ParentID = a.ItemID
UNION ALL
SELECT a.ItemID, NULL, a.Date
FROM @TableA a
)
SELECT a.ItemID, b.Date
FROM (
SELECT ItemID, Date, ParentID
,rn=ROW_NUMBER() OVER (PARTITION BY ItemID ORDER BY ParentID DESC)
FROM CTE
) a
INNER JOIN @TableA b ON a.ItemID = b.ItemID
WHERE rn=1
ORDER BY a.Date, ParentID, ItemID
Note that it only works for one level of parent-child hiearchy.
My thought question: Have you ever been told that your query runs too fast?
My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]
[url url=http://www.sqlservercentral.com/articles/St