Search code examples
sqloraclegreatest-n-per-group

Select MAX(DateTime) returning multiple lines


I'm trying to select the last MAX(DateTime) status from the table "Zee" but if the DateTime is the same it returns two lines, and I would like to get only the last one (maybe last inserted?).

here is the query:

SELECT Z."ID" AS ID,Z."A" AS A,Z."B" AS B,Z."C" AS C,Z."D" AS D
FROM ZEE Z
INNER JOIN
    (SELECT ID, A, B, MAX(C) AS C
    FROM ZEE
    GROUP BY A, B) groupedtt
ON Z.A = groupedtt.A
AND Z.B = groupedtt.B
AND Z.C = groupedtt.C
WHERE (
        Z.B = 103
     OR Z.B = 104
);

and the result:

enter image description here

Thanks,

Regards.


Solution

  • I usually use rank() for such things:

    select Z."ID" AS ID,Z."A" AS A,Z."B" AS B,Z."C" AS C,Z."D" AS D
    from (select Z.*, rank()over(partition by A,B order by C desc, rownum) r from ZEE Z
    )Z where Z.r=1