如何在sql中获取表的最后一条记录

时间:2017-04-04 11:49:24

标签: mysql

我在考勤表中有三个条目。但是我需要从考勤表中打印id的最后一个条目。我在单独的查询和单独查询的打印列表中计算了总持续时间。任何人请帮我解决这个问题。

查询打印总持续时间:

select SEC_TO_TIME(sum(case when a.endtime  IS NULL 
                         then time_to_sec(TIMEDIFF(NOW(),a.starttime))  
                         else time_to_sec(a.duration) 
                       end)
                   ) as duration
from attendance a
left join staff s on a.staffid=s.id
left join company c on a.companyid=c.companyid 
where DATE_FORMAT(a.createdon, '%Y/%m/%d') = DATE_FORMAT('2017-04-04', '%Y/%m/%d') and 
(a.employeecode ='A101' OR 'A101'='') and
(a.companyid=0 OR 0=0)
group by a.employeecode,a.companyid order by a.id desc

查询以打印详细信息:

select a.id, 
       a.starttime, 
       a.endtime,
       a.startlocation, 
       a.endlocation, 
       a.duration, 
       a.companyid, 
       a.employeecode, 
       a.staffid, 
       a.createdon, 
       a.createdby,
       a.lastmodifiedon,    
       a.reason, 
       a.comments,
       s.name as staffName, 
       c.company_name as companyName 
from attendance a
left joinstaff s on a.staffid=s.id 
left join company c on a.companyid=c.companyid 
where DATE_FORMAT(a.created_on, '%Y/%m/%d') = DATE_FORMAT('2017-04-04', '%Y/%m/%d') and 
(a.employeecode ='A101' OR 'A101'='') and 
(a.company_id=0 OR 0=0)
group by a.employeecode,a.companyid order by a.id desc

1 个答案:

答案 0 :(得分:0)

我通过将endtime设置为null来获得输出。

`select SEC_TO_TIME(sum(case when a.endtime IS NULL then  time_to_sec(TIMEDIFF(NOW(),a.starttime)) else time_to_sec(a.duration) end)) 
from attendance a left join staff s on a.staffid=s.id
left join company c on a.companyid=c.companyid 
where DATE_FORMAT(a.createdon, '%Y/%m/%d') = DATE_FORMAT('', '%Y/%m/%d') and 
(a.employeecode ='' OR ''='') and 
(a.companyid=0 OR 0=0)
group by a.employeecode,a.companyid order by a.id desc`