Question

I'm having a little headache to make a query, maybe someone can help with it.

My table fields (ID, FIELD1, FIELD2, STATUS, DATE).

Lets assume that I want to group by FIELD1 and FIELD2 and order by max(DATE). In my response I need to show the ID and STATUS field.

Is this possible?

In advance, thanks!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top