我需要从表中选择多个时间平均值。我可以使用多个查询来完成此操作,但我想知道如何将所有查询统一到一个查询中。
例如,我有这张表:
------------------------------------------------
| id | number | name | date | duration |
-------------------------------------------------
| 1 | 2 | SOMENAME | 2019-07-01 | 02:34:33 |
| 2 | 3 | SOMETHIN | 2019-03-05 | 01:54:31 |
| 3 | 2 | ANEWNAME | 2018-09-21 | 04:17:43 |
| 4 | 2 | SOMENAME | 2019-07-11 | 02:33:07 |
-------------------------------------------------
我的疑问:
SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(duration))) FROM mytable where number='2' and date LIKE '%2019-07%';
SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(duration))) FROM mytable where number='2' and date BETWEEN '2018-07-31 23:59:59' AND '2019-07-31 23:59:59';
SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(duration))) FROM mytable where number='2' and date BETWEEN '2018-07-31 23:59:59' AND '2019-07-31 23:59:59' and name like '%SOMENAME%' and duration > '00:00:01' group by name;
我已经尝试过,但没有成功:
SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(duration))) FROM mytable where number='2' and (date LIKE '%2019-07%' OR date BETWEEN '2018-07-31 23:59:59' AND '2019-07-31 23:59:59' OR date BETWEEN '2018-07-31 23:59:59' AND '2019-07-31 23:59:59' and name like '%SOMENAME%')
我想在单个查询中执行相同的查询,在平均值的左侧添加一个新列,并在其上添加自定义值。例如:
------------------------
|description | average |
------------------------
| month avg | 02:33:11 |
------------------------
| year avg | 02:17:19 |
------------------------
| year avg2 | 02:52:26 |
------------------------
你有什么提示吗?
最佳答案
您实际上可以在平均值中包含条件语句。例如
SEC_TO_TIME(AVG( IF(date LIKE '%2019-07%', TIME_TO_SEC(duration), NULL) )) as avgA,
SEC_TO_TIME(AVG( IF(date BETWEEN '2018-07-31 23:59:59' AND '2019-07-31 23:59:59', TIME_TO_SEC(duration), NULL) )) as avgB,
SEC_TO_TIME(AVG( IF(date BETWEEN '2018-07-31 23:59:59' AND '2019-07-31 23:59:59' and name like '%SOMENAME%' and duration > '00:00:01', TIME_TO_SEC(duration), NULL) )) as avgC
这只会对与日期条件匹配的行进行平均,因为平均中会忽略空值。
关于mysql - 如何在单个 MySQL 查询中选择多个平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57357426/