MySQL計算相鄰兩行某列差值的方法:首先透過【r1.rownum = r2.rownum - 1】來判斷兩個記錄是否為前後行;然後再使用TIMEDIFF函數來計算時間差即可。
【相關學習推薦:#mysql教學##(影片)】
MySQL計算相鄰兩行某列差值的方法:
#首先部落客在服務端有一個表來記錄司機上報上來的GPS點位信息,表結構如下:-- 司机GPS收集表 CREATE TABLE captainad_driver_gps_position ( id BIGINT NOT NULL auto_increment COMMENT '主键', business_id BIGINT DEFAULT NULL COMMENT '业务ID', device_mac VARCHAR (64) DEFAULT NULL COMMENT '设备MAC地址', device_imei VARCHAR (64) DEFAULT NULL COMMENT '设备IMEI', lat_lng VARCHAR (64) DEFAULT NULL COMMENT '纬经度', capture_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '捕获时间', create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间', PRIMARY KEY (id), KEY `idx_business_id` (`business_id`) USING BTREE ) ENGINE = INNODB DEFAULT CHARSET = utf8 COMMENT = '司机GPS收集';
SELECT (@rownum := @rownum + 1) AS rownum, tab.business_id, tab.device_mac, tab.capture_time FROM captainad_driver_gps_position tab, (SELECT @rownum := 0) r -- 声明变量 WHERE 1 = 1 AND DATE_FORMAT( tab.capture_time, '%Y-%m-%d' ) = '2019-06-28' ORDER BY tab.capture_time
SELECT t.business_id, t.device_mac, t.capture_time, t.tdiff FROM ( SELECT r1.business_id, r1.device_mac, r1.capture_time, TIMEDIFF( r2.capture_time, r1.capture_time ) AS 'tdiff' FROM ( SELECT (@rownum := @rownum + 1) AS rownum, tab.business_id, tab.device_mac, tab.capture_time FROM captainad_driver_gps_position tab, (SELECT @rownum := 0) r WHERE 1 = 1 AND DATE_FORMAT( tab.capture_time, '%Y-%m-%d' ) = '2019-06-28' ORDER BY tab.capture_time ) r1 LEFT JOIN ( SELECT (@INDEX := @INDEX + 1) AS rownum, tab.business_id, tab.device_mac, tab.capture_time FROM captainad_driver_gps_position tab, (SELECT @INDEX := 0) r WHERE 1 = 1 AND DATE_FORMAT( tab.capture_time, '%Y-%m-%d' ) = '2019-06-28' ORDER BY tab.capture_time ) r2 ON r1.business_id = r2.business_id AND r1.device_mac = r2.device_mac AND r1.rownum = r2.rownum - 1 ) t WHERE t.tdiff > '00:00:15'
r1.rownum = r2.rownum - 1來判斷兩筆記錄是否為前後行,然後再使用
TIMEDIFF函數來計算時間差,到此,我們的目標就達成了。
想了解更多程式設計學習,請關注php培訓欄位!
#
以上是MySQL如何計算相鄰兩行某列差值的詳細內容。更多資訊請關注PHP中文網其他相關文章!