SQL syntax error: near "("

SQL syntax error: near "("

当我尝试运行这个查询时:

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

我收到这个错误:

Error: near "(": syntax error
select my_alias1,my_alias2 from (select col1,col2,...) as A (my_alias1,my_alias2)

以上语法在SQL Server中有效。

要为派生 table 中的列添加别名,您需要在派生 table 中使用 AS。试试这个

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;

也开始使用 INNER JOIN 而不是旧式的逗号分隔连接

在 SQLite 中,子查询上的 AS 子句不能分配列名(而且一开始就不需要)。

要重命名(子)查询的输出列,您必须在 SELECT 子句中使用 AS:

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

假设SQL服务器的版本是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;