简体   繁体   中英

MySQL - How to subtract two datetime from the same table

I need help on a small problem with a subtraction in the same table and column

Well, iam creating a view, but the aplication generated the results of used time in tha same table and column.

My table have the following columns: id,field_id,object_id and value_date.

| ID | FIELD_ID | OBJECT_ID | VALUE_DATE          |
| 55 | 4        | 33        | 2016-12-18 19:02:00 |
| 56 | 5        | 33        | 2016-12-18 19:12:00 |
| 57 | 4        | 35        | 2016-12-18 19:30:00 |
| 58 | 5        | 35        | 2016-12-18 20:00:00 |

I do not have much knowledge in sql, but i have tried some functions like timestampdiff, period_siff and others examples in stackoverflow.com.

Someone help me to subtract ID 56 with field_id 5 by line with ID 55 and field_id 4 in object_id 33 in SQL to bring the result in minutes. Ex: 10 or 00:10:00

An article about this problem would already help me. Thank you very much!

Lets assume that you want result to be in day format then query will be :

SELECT DATEDIFF(day,startDate,endDate) AS 'Day'  
FROM table1;  

Find complete example here

The soluction is below:

select TIMESTAMPDIFF(MINUTE,F1.value_date,F2.value_date) as minutes, F1.value_date,F2.value_date,F1.object_id,F2.object_id,F1.field_id,F2.field_id
from otrs_tst.dynamic_field_value F1 
join otrs_tst.dynamic_field_value F2 on F1.object_id = F2.object_id
 where F1.field_id in ('4','5') 
 and F2.field_id in ('4','5') 
 and F2.field_id <> F1.field_id
 and F1.field_id < F2.field_id
 group by F1.object_id,F2.field_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM