简体   繁体   中英

MySQL select the average timedifference between two timestamp columns for a particular id in a table

I have a table visits that looks like this:

+--------------+-------------+------+-----+---------------------+----------------+
| Field        | Type        | Null | Key | Default             | Extra          |
+--------------+-------------+------+-----+---------------------+----------------+
| id           | int(11)     | NO   | PRI | NULL                | auto_increment |
| vis_id       | int(11)     | NO   | MUL | NULL                |                |
| unit         | int(11)     | NO   | MUL | NULL                |                |
| time_in      | timestamp   | NO   | MUL | CURRENT_TIMESTAMP   |                |
| time_out     | timestamp   | NO   | MUL | 0000-00-00 00:00:00 |                |
| in_username  | varchar(16) | NO   | MUL | NULL                |                |
| out_username | varchar(16) | NO   | MUL | NULL                |                |
+--------------+-------------+------+-----+---------------------+----------------+

I use this to keep track of visitors coming in and out of my building.

What I'd like is to be able to see the "average length of visit" in hours by a particular visitor (defined by vis_id ). If the average visit length is less than an hour it should round up to 1.

Here's an example of what I'd like for output:

+--------+------+----------+
| vis_id | unit | avg_time |
+--------+------+----------+
|    156 |  216 | 5        |
|   1230 |  103 | 2        |
|    533 |  112 | 1        |  
|    802 |  201 | 3        |
|   1445 |  431 | 4        |
+--------+------+----------+

Suggestions?

Use AVG() grouping function. As far as I see, you'll need two grouping fields, like below:

SELECT 
  vis_id,
  unit,
  ROUND(AVG((UNIX_TIMESTAMP(time_out)-UNIX_TIMESTAMP(time_in))/3600)) AS avg_time
FROM
  visits
GROUP BY
  vis_id,
  unit

Note, that I'm using ROUND() since you've not defined rules for dealing with non-integer values. ROUND() will use algebraic rule, but may be you'll want to drop non-integer part. Then look to FLOOR() - or, instead, add integer part (ie round to greatest) - then look to CEIL()

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