0

如何获取最近的儿童记录的日期?在 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
4

1 回答 1

1

您正在寻找日期字段上的 MAX 聚合函数与 MOPID 上的 group by 组合,以对所有类似 ID 进行分组并返回最近的日期。Distinct 对您不起作用,因为您有不同的日期。通过仅返回最大值,您将获得 1 个日期,并使用 group by 生成 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
于 2013-08-26T18:28:54.377 回答