选择MAX(DateTime)返回多行

时间:2017-09-08 13:14:53

标签: sql oracle greatest-n-per-group

我试图从表格中选择最后一个MAX(日期时间)状态" Zee"但是如果DateTime是相同的,它返回两行,我想只得到最后一行(可能最后插入?)。

这是查询:

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
);

结果:

enter image description here

谢谢,

问候。

2 个答案:

答案 0 :(得分:1)

我通常使用rank()来做这些事情:

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

答案 1 :(得分:1)

使用ROW_NUMBER()分析函数(您还将消除自联接):

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;