Oracle - 选择最大记录(最新日期)

时间:2013-11-19 09:57:59

标签: sql oracle max

我正在使用ORACLE 8.0。我有一个柱面主机,一个事务日志头文件和一个事务日志尾部(详细信息)。结构如下:

Mcylinder:ID,CSTAGE, TCYLINDERHD:logno,logdate,accode,docref,mmode, Tcylindertl:logno,id

  1. 对于日志标题,会有许多日志尾部
  2. 对于mcylinder中CSTAGE为4的每个Cylinders,我想从日志文件中获取mmode(与CSTAGE相同)= 4的柱面事务的最新日期的详细信息。
  3. 我尝试了几种方法但没有成功。我尝试的最后一个sql如下:

        SELECT cout.ID,tlog.LOGNO,tlog.LOGDATE,tlog.ACCODE,tlog.DOCREF
    FROM
    (SELECT "ID" FROM "MCYLINDER" WHERE "CSTAGE"=4 ORDER BY "ID") cout,
    (SELECT  "LOGNO","LOGDATE","ACCODE","DOCREF" FROM "TCYLINDERHD" WHERE "MMODE" = 4 order by "LOGNO") tlog,
    (SELECT  MAX(a."LOGDATE"),b."ID",b."LOGNO" FROM "TCYLINDERHD" a,"TCYLINDERTL" b
      WHERE (a."MMODE" = 4) AND  (a."LOGNO" = b."LOGNO") GROUP BY b."ID" order by b."ID",b."LOGNO") mlog
    WHERE (cout.ID=mlog.ID AND mlog.LOGNO=tlog.LOGNO)
    order by cout.ID;
    

    SQL显示错误说明缺少paranthesis。我不知道为什么。这也是正确的方法吗?

    请帮忙。

    提前完成。

1 个答案:

答案 0 :(得分:1)

首先,删除所有括号,在Oracle中你不需要它们。 其次,如果我正确理解了您要实现的目标,请尝试以下查询。如果它没有帮助,请考虑在您的问题中添加样本数据和所需结果,这样可以更轻松地为您提供帮助。

SELECT t1.id, t2.logno, t3.logdate, t3.accode, t3.docref FROM MCYLINDER t1 
       INNER JOIN TCYLINDERTL t2 ON t1.id = t2.id
       INNER JOIN TCYLINDERHD t3 ON t2.logno = t3.logno
WHERE t1.cstage = 4
      AND t3.mmode = 4
      AND t3.logdate >= ALL (SELECT t4.logdate FROM TCYLINDERHD t4 
                                    INNER JOIN TCYLINDERTL t5 ON t4.logno = t5.logno
                             WHERE t5.id = t2.id AND t4.mmode = t3.mmode)