SQL syntax error: near "("

Rohit N. picture Rohit N. · Mar 4, 2016 · Viewed 7.5k times · Source

When I try to run this query:

select branch_no, max (avg_salary)
from (select allocatedto, avg (salary)
      from staff, worker
      where staff.staff_no = worker.staff_no
      group by allocatedto) 
      as branch_avg (branch_no, avg_salary);

I get this error:

Error: near "(": syntax error

Answer

Pரதீப் picture Pரதீப் · Mar 4, 2016
select my_alias1,my_alias2 from (select col1,col2,...) as A (my_alias1,my_alias2)

The above syntax is valid in SQL Server.

To alias the column in derived table you need to use AS inside the derived table. Try this

SELECT Max (avg_salary)
FROM   (SELECT allocatedto  AS branch_no,
               Avg (salary) AS avg_salary
        FROM   staff
               INNER JOIN worker
                       ON staff.staff_no = worker.staff_no
        GROUP  BY allocatedto) AS branch_avg;

Also start using INNER JOIN instead of old style comma separated join