简体   繁体   中英

SQL syntax error: near “(”

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

In SQLite, an AS clause on a subquery cannot assign column names (and it is not needed in the first place).

To rename the output columns of a (sub)query, you must use AS in the SELECT clause:

SELECT branch_no,
       max(avg_salary) AS avg_salary
FROM (...);

assume the version of SQL Server is 2008 R2,

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)
group by branch_no;

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.

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