如何在 MySQL 時間列中得到平均值?


要獲取時間列的平均值,使用以下語法。它將以時間格式給出平均值:−

SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(yourColumnName))) as anyVariableName from yourTableName;

為了理解上述概念,讓我們建立一個表。以下為查詢:−

mysql> create table AverageOnTime
   −> (
   −> PunchInTime time
   −> );
Query OK, 0 rows affected (0.61 sec)

使用 insert 命令將時間值插入表中。插入記錄的查詢如下:−

mysql> insert into AverageOnTime values('00:00:40');
Query OK, 1 row affected (0.20 sec)

mysql> insert into AverageOnTime values('00:02:50');
Query OK, 1 row affected (0.15 sec)

mysql> insert into AverageOnTime values('00:03:30');
Query OK, 1 row affected (0.13 sec)

mysql> insert into AverageOnTime values('00:04:55');
Query OK, 1 row affected (0.14 sec)

使用 select 語句從表中顯示時間。查詢如下:−

mysql> select *from AverageOnTime;

以下是輸出:−

+-------------+
| PunchInTime |
+-------------+
| 00:00:40    |
| 00:02:50    | 
| 00:03:30    |
| 00:04:55    |
+-------------+
4 rows in set (0.00 sec)

現在要獲取時間列的平均值,使用以下查詢。查詢如下:−

mysql> SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(PunchInTime))) as Average from AverageOnTime;

以下是顯示平均值的輸出:−

+---------------+
| Average       |
+---------------+
| 00:02:58.7500 |
+---------------+
1 row in set (0.08 sec)

更新於:30-Jul-2019

2K+ 瀏覽量

開啟你的 事業

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.