简体   繁体   English

如何在MySQL中对相似的条目组执行平均

[英]how to perform average for similar group of entries in mysql

+----------+--------+
| emp_name | rating |
+----------+--------+
| Sameer   |      4 |
| Sameer   |    9.8 |
| Sameer   |      9 |
| Sameer   |      7 |
| Sameer   |    8.2 |
| Sameer   |    9.5 |
| Sameer   |     10 |
| Ashwath  |      9 |
| Ashwath  |      4 |
| Ashwath  |      9 |
+----------+--------+

I just started learning SQL and I wrote a query and got the above output but i want to display the averege rating of Sameer and Ashwath instead of rating, how can i do it? 我刚刚开始学习SQL,我写了一个查询并获得了上述输出,但是我想显示Sameer和Ashwath的平均评分而不是评分,我该怎么做?

Query: 查询:

SELECT
    emp_name,
    bus.rating
FROM employees
JOIN drives
    ON employees.emp_id = drives.emp_id
JOIN bus
    ON bus.bus_no = drives.bus_no
WHERE
    drives.emp_id IN (select emp_id from drives group by emp_id having count(bus_no) > 2);

Just aggregate by employee and take the average rating: 只需按员工进行汇总并得出平均评分:

SELECT
    emp_name,
    AVG(bus.rating) AS avg_rating
FROM employees
INNER JOIN drives
    ON employees.emp_id = drives.emp_id
INNER JOIN bus
    ON bus.bus_no = drives.bus_no
WHERE
    drives.emp_id IN (SELECT emp_id FROM drives
                      GROUP BY emp_id HAVING COUNT(bus_no) > 2)
GROUP BY
    emp_name;

As you are learning SQL, it's better to do the right things : 在学习SQL时,最好做正确的事情:

Try to always use INNER JOIN OR LEFT JOIN. 尝试始终使用INNER JOIN或LEFT JOIN。 Using IN is more "expensive" than doing an INNER JOIN or LEFT JOIN. 使用IN比进行INNER JOIN或LEFT JOIN更“昂贵”。 Last, when you use an aggregate function (COUNT, SUM, AVG) you need to use a GROUP BY If I rewrite your query here is what I would do : 最后,当您使用聚合函数(COUNT,SUM,AVG)时,您需要使用GROUP BY。如果我在这里重写查询,我将执行以下操作:

 SELECT
        emp_name,
       AVG(bus.rating)
 FROM employees
 INNER JOIN drives on employees.emp_id=drives.emp_id 
 INNER  JOIN
   (select emp_id, count(bus_no) from drives
     group by emp_id having count(bus_no) > 2 ) AS   d 
        ON drives.emp_id = d.emp_id
 INNER   JOIN bus
        ON bus.bus_no = drives.bus_no
  GROUP BY emp_name

Here is a famous image to explain all the joins 这是一张解释所有联接的著名图像 Sql联接

从表GROUP BY emp_name中选择emp_name,avg(rating)

尝试这个 -

$sql = "SELECT emp_name, AVG(rating) as avg_rating FROM table_name GROUP BY emp_name";

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

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