简体   繁体   中英

Group mysql query results in php generated table and add results of table row together with same id

I have a large MySQL table which looks like this:

job_number        time_on        time_off
111               18:50:10       18:51:18
222               18:13:09       19:33:42
111               07:12:04       08:30:20
333               10:34:03       12:53:10
444               14:54:25       12:11:04
444               10:31:48       16:34:53
111               17:21:41       20:21:41
(type: Varchar)   (type: time)   (type: time)

I want to find the difference between the time_on and time_off fields for each job_number and echo them in the $total_time column.
If there are multiple rows with the same job_number (111, 444), i want to be able to find the difference between the time_on and the time_off for that row but also add these values together. I would like to make sure there is only one row of each unique job number with the combined times like so:

Job    Total Time // ($total_time = $time_off - $time_on)
111    04:19:34 // ((18:51:18 - 18:50:10) + (08:30:20 - 07:12:04) +  (20:21:41 - 17:21:41))
222    01:20:33 // (19:33:42 - 18:13:09)
333    02:19:07 // (12:53:10 - 10:34:03)
444    08:46:26 // ((16:34:53 - 10:31:48) + (14:54:25 - 12:11:04))

the results will be formatted in a simple table like so:

<table>  
    <tr>  
        <th>Job</th>  
        <th>Total Time</th>  
    </tr>  
    <tr>  
        <td>111</th>  
        <td>04:19:34</th>
    </tr>
    <tr>  
        <td>222</th>  
        <td>01:20:33</th>
    </tr>
    ...
</table>

How would i go about doing this? I would prefer to use PHP to achieve this. Any help would be greatly appreciated. Thankyou

You could do it in SQL:

SELECT   job_number,
         SEC_TO_TIME(SUM(TIME_TO_SEC(time_off) - TIME_TO_SEC(time_on)))
FROM     my_table
GROUP BY job_number

See it on sqlfiddle .

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