0

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.

H. Eberhardt
  • 79
  • 10

2 Answers2

1

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
wolfrevokcats
  • 2,100
  • 1
  • 12
  • 12
1

Use the ROW_NUMBER() analytic function (you will also eliminate the self-join):

SELECT ID, A, B, C, D
FROM (
  SELECT ID,
         A,
         B,
         C,
         D,
         ROW_NUMBER() OVER ( PARTITION BY A, B ORDER BY C DESC ) As rn
  FROM   ZEE
)
WHERE   rn = 1;
MT0
  • 143,790
  • 11
  • 59
  • 117