我有一张包含下列专栏的表格:
我想用第2行PATIENT_IN_TIME减去第1行PATIENT_IN_TIME,并将结果以分钟为单位保存到AVG_CHECKUP_TIME。
假设表格中有5个条目。
|1|2|2018-03-22 02:49:51|NULL|
|2|2|2018-03-22 02:56:37|NULL|
所以我想找到两行的差异并保存最后一列中的分钟。所以,输出看起来像,
|1|2|2018-03-22 02:49:51|7|
|2|2|2018-03-22 02:56:37|NULL|
如果您需要更多信息,请与我们联系。
答案 0 :(得分:3)
create table tbl ( id int auto_increment primary key, doctor_id int, patient_in_time datetime, avg_checkup_time datetime ); insert into tbl values (1, 2, '2018-03-22 02:49:51', null), (2, 2, '2018-03-22 02:56:37', null), (3, 2, '2018-03-22 03:00:15', null), (4, 2, '2018-03-22 03:03:37', null);
select t1.id, t1.doctor_id, t1.patient_in_time, timestampdiff(minute, t1.patient_in_time, (select patient_in_time from tbl where id = t1.id +1)) diff from tbl t1
id | doctor_id | patient_in_time | diff -: | --------: | :------------------ | ---: 1 | 2 | 2018-03-22 02:49:51 | 6 2 | 2 | 2018-03-22 02:56:37 | 3 3 | 2 | 2018-03-22 03:00:15 | 3 4 | 2 | 2018-03-22 03:03:37 | null
dbfiddle here
根据评论,如果订单由patient_in_time
设置,那么您可以使用以这种方式返回下一行的标量子查询:
select t1.id, t1.doctor_id, t1.patient_in_time, timestampdiff(minute, t1.patient_in_time, (select patient_in_time from tbl where patient_in_time > t1.patient_in_time order by patient_in_time asc limit 1)) diff from tbl t1 order by patient_in_time
id | doctor_id | patient_in_time | diff -: | --------: | :------------------ | ---: 1 | 2 | 2018-03-22 02:49:51 | 6 2 | 2 | 2018-03-22 02:56:37 | 3 3 | 2 | 2018-03-22 03:00:15 | 3 4 | 2 | 2018-03-22 03:03:37 | null
dbfiddle here