最近的儿童记录是关键的

时间:2013-08-26 18:09:56

标签: sql oracle

如何获取最新儿童记录的日期?在SQL中,我正在尝试获取最新的MOPNOTES.MOPNOTEDATE。我还希望每个MOPACTIVITY.MOPID只有一条记录。任何方向都将不胜感激。

SELECT DISTINCT MOPACTIVITY.MOPID,
MOPNOTES.MOPNOTEDATE 
FROM MOPUSER.MOPACTIVITY INNER JOIN MOPUSER.MOPNOTES ON MOPACTIVITY.MOPID=MOPNOTES.MOPID
WHERE MOPACTIVITY.MOPEND BETWEEN TRUNC(SYSDATE-1) + INTERVAL '12:00' HOUR TO MINUTE AND TRUNC(SYSDATE) + INTERVAL '9:00' HOUR TO MINUTE
AND UPPER(MOPACTIVITY.MOPSTATUS) = 'COMPLETE'
AND UPPER(MOPACTIVITY.MOPNOTIFICATIONSENT) LIKE '%TRUE%'
ORDER BY MOPACTIVITY.MOPID

1 个答案:

答案 0 :(得分:1)

您正在寻找日期字段上的MAX聚合函数以及与MOPID组合在一起的所有类似Ids的组并返回最近的日期。因为你有不同的约会,所以区别不适合你。通过仅返回最大值,您将获得1个日期,并使用该组生成1个ID。

SELECT MOPACTIVITY.MOPID, Max(MOPNOTES.MOPNOTEDATE)
FROM MOPUSER.MOPACTIVITY 
INNER JOIN MOPUSER.MOPNOTES 
  ON MOPACTIVITY.MOPID=MOPNOTES.MOPID
WHERE MOPACTIVITY.MOPEND BETWEEN TRUNC(SYSDATE-1) + INTERVAL '12:00' HOUR TO MINUTE AND TRUNC(SYSDATE) + INTERVAL '9:00' HOUR TO MINUTE
AND UPPER(MOPACTIVITY.MOPSTATUS) = 'COMPLETE'
AND UPPER(MOPACTIVITY.MOPNOTIFICATIONSENT) LIKE '%TRUE%'
GROUP BY MOPACTIVITY.MOPID
ORDER BY MOPACTIVITY.MOPID