如何在mysql中对类似的条目组执行平均

时间:2018-02-19 10:35:41

标签: 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 |
+----------+--------+

我刚刚开始学习SQL并且我写了一个查询并得到了上面的输出,但是我想显示Sameer和Ashwath的评级,而不是评级,我该怎么办?

查询:

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

4 个答案:

答案 0 :(得分:2)

只按员工汇总并取平均评分:

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;

答案 1 :(得分:0)

在学习SQL时,最好做正确的事情:

尝试始终使用INNER JOIN或LEFT JOIN。使用IN比执行INNER JOIN或LEFT JOIN更“昂贵”。 最后,当您使用聚合函数(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

这是一张着名的图片来解释所有连接Sql Joins

答案 2 :(得分:-1)

SELECT emp_name,avg(rating)FROM table GROUP BY emp_name

答案 3 :(得分:-1)

试试这个 -

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