mysql retrieve difference between current and last

2019-08-31 00:18发布

For the below table, i would like to get the difference between last hour and current hour for col-D and col-E for each of the site. As part of that I am trying to first get the latest (current) hour entries for each of the site, but the following query is only listing me the entries with endTime as 01:00:00, when i have entries upto 9.00AM

select distinct(mmeName), endDate, endTime, c_ratio, set_time from attach where
 type='INIT' and Date(endDate)=curDate() and 
Time(endTime) >= DATE_ADD(Time(endTime), INTERVAL -1 HOUR) group by mmeName;

Any help would be appreciated for the immediate issue and as well finding the difference between current and last hour.

enter image description here

标签: mysql time hour
1条回答
看我几分像从前
2楼-- · 2019-08-31 01:12

EDITED

I think this is what you are looking for. This will give you any records where the endTime is one hour prior to the latest current time for each mmeName. The 'max' sub-select gets the latest end datetime for each mmeName, and the join back matches on record exactly one hour prior to that.

SELECT  mmeName, endDate, endTime, c_ratio, set_time 

FROM    attach a

        JOIN 
        (SELECT  mmeName, CONCAT(endDate, ' ' , endTime) max_endDateTime
         FROM    attach 
         WHERE   type = 'INIT' 
         ORDER BY endDate DESC, endTime DESC
        ) AS max ON max.mmeName = a.mmeName
                AND max.max_endDateTime = DATE_ADD(CONCAT(endDate, ' ' , endTime), INTERVAL 1 HOUR)

WHERE   type = 'INIT'
;

ORIGINAL

select  mmeName, endDate, endTime, c_ratio, set_time 

from    attach 

where   type='INIT' and Date(endDate)=curDate() and 
        endTime >= DATE_SUB(now(), INTERVAL -1 HOUR) 

group by mmeName;

Note: If there are multiple matching records for a given mmeName, this query will just grab one of them.

EDITED: You need drop the TIME() functions from the WHERE clause. Both would have the date and time and if you didn't, if you ran it between 12:00 AM to 1:00 AM it would not return any results.

查看更多
登录 后发表回答