如何在单个MySQL查询中选择多个平均值?

时间:2019-08-05 11:13:29

标签: mysql mariadb average

我需要从一个表中选择多个时间平均值。我可以通过多个查询来做到这一点,但是我想知道如何在一个查询中统一所有查询。

例如,我有这张桌子:

------------------------------------------------
| 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 |
------------------------

您有什么提示吗?

2 个答案:

答案 0 :(得分:2)

您实际上可以将条件语句包括在平均值中。例如

{{1}}

这将仅对符合日期条件的行求平均值,因为在平均值中会忽略空值。

答案 1 :(得分:0)

SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(t1.duration))) t1_avg_duration,
       SEC_TO_TIME(AVG(TIME_TO_SEC(t2.duration))) t2_avg_duration,
       SEC_TO_TIME(AVG(TIME_TO_SEC(t3.duration))) t3_avg_duration
  FROM mytable as t1,mytable as t2,mytable as t3
 where t1.number='2'
   and t1.number = t2.number
   and t2.number = t3.number
   and t1.date LIKE '%2019-07%'
   and t2.date BETWEEN '2018-07-31 23:59:59' AND '2019-07-31 23:59:59'
   and t3.date BETWEEN '2018-07-31 23:59:59' AND '2019-07-31 23:59:59' 
   and t3.name like '%SOMENAME%' and t3.duration > '00:00:01' group by t3.name;

或者如果可以多行就简单地合并所有查询

SELECT 'Custom text' as text1,SEC_TO_TIME(AVG(TIME_TO_SEC(duration))) FROM mytable where number='2' and date LIKE '%2019-07%';
union
SELECT 'Custom text' as text2,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';
union
SELECT 'Custom text' as text3,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;