如何使用max函数获取db2中的最后一条记录

时间:2013-02-04 01:46:11

标签: sql db2

我想通过使用max()函数获取该表的最后一条记录。

查询

select oafaci, oaorno, min(obfded) ,max(oblded) from mvxcdtpusd.oohead join mvxcdtpusd.ooline on oacono = obcono and oaorno = oborno and oafaci = obfaci and oawhlo = obwhlo where obitno like '19140%' and OBCONO = 888 group by OAFACI, OAORNO

结果

OAFACI  OAORNO      FDate            LDate
812 0000556215  20130109    20130109
812 0000554203  20130102    20130102
812 0000553769  20121017    20121017
812 0000554204  20130130    20130130
812 0000556214  20121024    20121024
812 0000556216  20130206    20130206

从结果表中 - 我想要以下数据。

欲望结果

812 0000556216  20130206    20130206

需要帮助才能使用max()

获取最后一条记录

2 个答案:

答案 0 :(得分:6)

为什么需要才能使用max()功能?如果这是作业,你应该在问题中说明。

获得最后一条记录的最佳方法是:

select *
from t
order by date
fetch first 1 row only

答案 1 :(得分:2)

尝试 此查询,

SELECT  *
FROM    tablename
WHERE   OAFACI = 812 AND
        OAORNO = (SELECT MAX(OAORNO) 
                    FROM tableName
                    WHERE OAFACI = 812)

<强>更新

SELECT  a.*
FROM    tableName a
        INNER JOIN 
        (
            SELECT  OAFACI, MAX(FDATE) max_date
            FROM    tableName
            GROUP   BY OAFACI
        ) b ON  a.OAFACI = b.OAFACI AND
                a.FDATE = b.max_date
-- WHERE    a.OAFACI = 812