简体   繁体   English

计算MySQL中其他平均值的平均值

[英]Calculate the average of other averages in MySQL

I have this table where I want to calculate the average response time from all users based on the cat_id and from a join based on the user_id 's country which are stored in another table. 我有这个表,我想计算基于所有用户的平均响应时间cat_id并从join基础上, user_id其存储在另一个表的国家。

What is the proper way to find the average time based on the user's country? 根据用户所在的国家/地区查找平均时间的正确方法是什么?

+---------+--------+-------+-------+-------+-------+-------+-------+-------+
| user_id | cat_id | time1 | time2 | time3 | time4 | time5 | time6 | time7 |
+---------+--------+-------+-------+-------+-------+-------+-------+-------+
|      11 |      1 | 10000 |  3500 | 10000 | 10000 |  7000 |  6000 |  6500 |
|       0 |      1 |  6139 |  2640 |  5438 |  8136 |  7157 |  8723 |  4677 |
|      11 |      3 |  7500 |  5500 | 10000 |  5500 |  7500 |  4000 |  9500 |
|       0 |      3 |  7462 |  8907 |  7513 |  4181 |  7275 |  2074 |  4444 |
|       1 |      1 |  8500 |  2000 |  8500 |  1500 | 10000 |  6500 | 10000 |
|       0 |      1 |  8885 |  7240 |  2153 |  6115 |  6330 |  6151 |  4325 |
|       1 |      1 | 10000 |  3000 | 10000 |  5500 | 10000 |  9000 | 10000 |
|       0 |      1 |  6188 |  3280 |  4725 |  5662 |  3344 |  8792 |  7560 |
|       1 |      4 |  4000 |  4500 | 10000 |  5000 |  3000 |  1500 |  2112 |
|       0 |      4 |  2750 |  4861 |  3413 |  4174 |  3080 |  3213 |  7932 |
+---------+--------+-------+-------+-------+-------+-------+-------+-------+

I've tried: (AVG(time1 + time 2 + ... + time7) / 7) but when I cross-check the results are not correct. 我尝试过: (AVG(time1 + time 2 + ... + time7) / 7)但是当我交叉检查结果不正确时。

Thanks in advance for any help :) 在此先感谢您的帮助:)

First of all there's a problem with your parenthesis, which should be 首先,您的括号有问题,应该是

AVG((time1 + time2 + ... + time7) / 7)

Then you may need to add something in your group by clause, depending on the level you want the average to be calculated at. 然后,您可能需要在group by子句中添加一些内容,具体取决于要计算平均值的级别。

首先,您应该计算行(time1 + time2 + ... time7)/7平均值,然后计算所有行的AVG((time1 + time2 + ... time7)/7)

I think your problem is taking an average of averages. 我认为您的问题是取平均值。 I would first calculate the sum and count for each row and left join to add the country. 我将首先计算每一行的总和和计数,然后左加以添加国家/地区。 Once you have your tabular data, you can summarize and do averages across country, cat, or both. 获得表格数据后,您可以汇总国家/地区,类别或两者的平均值并进行平均值计算。 Something like this: 像这样:

select country, cat_id, (sum(total_time)/sum(count)) as avg_response_time
from (
select a.user_id
      ,a.cat_id
      ,b.country
      ,(a.time1 + a.time2 + a.time3 + a.time4 + a.time5 + a.time6 + a.time7) as total_time
      ,7 as count
from a
left outer join b
on a.user_id = b.user_id
)
group by country, cat_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM