I think what you seem to want is just the "newest" version of each field1/field2 combination. There are a couple of ways to do this, but doing a correlated sub-select would probably be the easiest (not necessarily the fastest, but pretty performant):
SELECT
FIELD1
,FIELD2
FROM fields A
WHERE date = (
SELECT MAX(date)
FROM fields B
WHERE A.field1 = b.field1
AND A.field2 = b.field2
)
Obviously, an index on field1, field2, date
would make this run a little faster.
My guess is that one of your performance issues is that the database has to create an internal work file in order to do the ORDER BY
in your WITH
clause... which isn't actually needed. You're already getting the "max" date for each combination, and then ordering those "max" combinations by the max_date
. Then, you're doing an IN
, and order of the rows doesn't matter there.