+----------+--------+
| 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?
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 :
Try to always use INNER JOIN OR LEFT JOIN. Using IN is more "expensive" than doing an INNER JOIN or 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 :
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
从表GROUP BY emp_name中选择emp_name,avg(rating)
尝试这个 -
$sql = "SELECT emp_name, AVG(rating) as avg_rating FROM table_name GROUP BY emp_name";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.