从查询生成的表中获取最后一行

时间:2019-09-18 09:00:55

标签: sql oracle

大家好,我写了一个查询,该查询将给我雇员一段时间的进出时间,因为我的表有很多进出时间,我只想根据时间戳获取倒数时间,这里是查询为此

select
fullname,direction,to_char(((TO_DATE('19700101','yyyymmdd') + (tstamp/24/60/60) + 6/24)), 'dd-mm-yyyy  hh12:mi:ss PM') as Time,
gate,lane,employment.employeeid,NATIONALID,departmentname,designation.designationname
from eofficeuat.entrylog_cpa
join eofficeuat.employee on entrylog_cpa.hrrecordid=employee.hrrecordid
join eofficeuat.employment on employee.hrrecordid=employment.hrrecordid
join eofficeuat.designation on employment.designationid=designation.designationid
join eofficeuat.department on employment.departmentid=department.departmentid
where department.departmentname = 'SECURITY'
and tstamp >= 1568764800 and tstamp < (select (sysdate - date '1970-01-01') * 86400000 from dual)
/*and tstamp in (select max(tstamp) from eofficeuat.entrylog_cpa)*/
/*and rownum >= (select count(tstamp) from eofficeuat.entrylog_cpa)*/
and fullname='A.K.M.TOWHID SARKER'
order by fullname asc;

此查询给出此结果

 full name            direction   time
 ---------            ---------   ----
 A.K.M.TOWHID SARKER  out         18-09-2019  01:41:35 PM
 A.K.M.TOWHID SARKER  out         18-09-2019  01:29:08 PM

但是我只想要此结果的最后一行。你能帮我怎么做?

1 个答案:

答案 0 :(得分:0)

您可以包装查询并使用ROW_NUM()

SELECT *
FROM (
    -- your query with an ORDER BY clause
) x WHERE ROWNUM = 1

请注意,这将选择结果集中的第一行。如果要最后一行,则需要更改ORDER BY子句以将相反的方式排在第一位。

如果您运行的是Oracle 12c或更高版本,则无需包装查询,可以使用FETCH FIRST ROW ONLY子句。

SELECT ...
FROM ...
ORDER BY ...
FETCH FIRST ROW ONLY