I have a table with data similar to the following:
The longer I work on this, the uglier my SQL is getti
Assuming you are using SQL Server 2005 or >
Try this:
WITH Data AS
(
SELECT *,
COALESCE([DateCreated], [DateUpdated]) AS LastUpdated,
ROW_NUMBER() OVER(PARTITION BY State ORDER BY COALESCE([DateCreated], [DateUpdated]) DESC) Position
FROM a
WHERE NOT EXISTS
(
SELECT 1
FROM b
WHERE a.State = b.State
AND a.foo <> b.foo
)
)
SELECT State, foo, LastUpdated
FROM Data
WHERE Positon = 1