2015-05-25 84 views
0

我試圖找到在第一次和最後一次讀數之間有最長時間的行的產品EPC。表中可以有多個條目。如何選擇日期間差異最大的列 - MySQL

無論我做什麼,我都無法想出如何獲取此信息。

這是表:

CREATE TABLE IF NOT EXISTS `Track_Record` (
    `longitude` varchar(15) NOT NULL , 
    `lattitude` varchar(15) NOT NULL , 
    `datetime` DATETIME NOT NULL, 
    `EPC` varchar(200) NOT NULL , 
    `ip` varchar(50) NOT NULL , 

    PRIMARY KEY (ip, EPC, datetime), 
    FOREIGN KEY (EPC) REFERENCES Product(EPC) ON DELETE CASCADE, 
    FOREIGN KEY (ip) REFERENCES RFID_Reader(ip) ON DELETE CASCADE 
); 

而且這是在表中的數據:

Track_Record (ip, longitude, lattitude, datetime, EPC) 
VALUES 
('000.111.222', '27.4667 S', '153.0333 E', '2014-11-05 18:56:46', '03.0000A89.00016F.000169DCD'), 
('000.111.222', '27.4667 S', '153.0333 E', '2015-05-12 13:21:16', '03.0000A89.00016F.000169DCD'), 
('555.666.777', '22.2783 N', '114.1747 E', '2012-07-19 12:22:16', '04.0000A89.00016F.000169DCD'), 
('000.111.222', '27.4667 S', '153.0333 E', '2011-03-01 11:43:26', '03.0000A89.00016F.000169DCD'), 
('555.666.777', '22.2783 N', '114.1747 E', '2014-09-02 18:53:14', '06.0000A89.00016F.000169DCD'), 
('222.333.444', '59.3500 N', '18.0667 E', '2015-10-15 18:23:18', '04.0000A89.00016F.000169DCD'), 
('333.444.555', '15.7833 S', '47.8667 W', '2015-02-22 19:53:16', '01.0000A89.00016F.000169DCD'), 
('444.555.666', '51.5072 N', '0.1275 W', '2013-01-11 22:21:15', '04.0000A89.00016F.000169DCD'); 

如果有人有我如何才能得到這個信息的想法,我將非常感激任何幫助你可以提供。

感謝 科瑞

回答

3

聽起來像是你需要的maxminepc之間的差異,所以這樣的:

select epc, max(`datetime`), min(`datetime`), timediff(max(`datetime`), min(`datetime`)) 
    from Track_Record 
    order by timediff(max(`datetime`), min(`datetime`)) desc 
    limit 1; 

從樣本數據上述結果:

+-----------------------------+---------------------+---------------------+--------------------------------------------+ 
| epc       | max(`datetime`)  | min(`datetime`)  | timediff(max(`datetime`), min(`datetime`)) | 
+-----------------------------+---------------------+---------------------+--------------------------------------------+ 
| 03.0000A89.00016F.000169DCD | 2015-10-15 18:23:18 | 2011-03-01 11:43:26 | 838:59:59         | 
+-----------------------------+---------------------+---------------------+--------------------------------------------+ 
1 row in set, 1 warning (0.00 sec)