10110
10110

Reputation: 2665

Get Average Salary for each employee

I started learning PL/SQL a few days ago from scratch (NO SQL background) and now I'm trying to play with aggregate functions and was attempting to get the average salary for each employee.

Table would look like this:

Table 1:

enter image description here

And I'd like to see this:

Table 2:

enter image description here

At the moment, I'm doing something like this:

SELECT
  employee, AVG(salary)
FROM
  employees

GROUP BY employee, salary

But it's giving the a result identical to table 1.

In other words, I'd like to learn how to consolidate or aggregate a number of rows into a single one. Basically, calculate the average salary for each employee and display just one row with the employee and it's respective AVG(SALARY).

Is this not possible or am I just doing something wrong?

Thank you.

Upvotes: 0

Views: 1571

Answers (2)

Fahmi
Fahmi

Reputation: 37473

Try this: Just remove salary column from group by

 SELECT employee, AVG(salary) FROM employees
   GROUP BY employee

Upvotes: 4

10110
10110

Reputation: 2665

This is super awkward for me, but I won't delete the question just in case someone runs into the same issue as me.

Error was in the group by, I should have grouped only by employee.

For some reason, I thought I had to group by every column that was present in the SELECT.

So, query should be:

SELECT
    employee, AVG(salary)
FROM
    employees  
GROUP BY 
    employee -- ERROR WAS HERE, leave just employee. -.-

I'm sorry for not noticing a before, rookie mistake.

Upvotes: 1

Related Questions