SQL syntax error: near "("

时间:2016-03-04 18:11:44

标签: sql sqlite subquery derived-table

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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;