【问题标题】:I am trying to correct this error code in T-SQL that states that I have an invalid column我正在尝试更正 T-SQL 中的此错误代码,该代码指出我的列无效
【发布时间】:2011-03-08 20:05:29
【问题描述】:

这是我最初的问题:

“What would be the correct syntax and join (if any) of a subquery that would return all of the employees first and last name from the employee’s table, and return their department name from the department table, but only those employees who more than the average salary for their department? Thanks for your answers”

在使用了 Mitch Wheat 的示例(并接受了他当之无愧的训诫)之后,我在我的数据库中的 DEPARTMENT 表中添加了一个列并实现了以下代码:

ALTER TABLE DEPARTMENTS  
ADD Salary money
GO
select First_Name, Last_Name, department_Name  
from Employees e join  
   (select Department_Name,AVG(Salary) AS averageSalary  
     from DEPARTMENTS d  
     join Employees e ON e.Department_Id=d.Department_Id  
     group by  Department_Name) ds 
on ds.averageSalary=e.Employee_Id 
where e.salary>ds.AverageSalary 

但是,我仍然收到此错误:

Msg 207, Level 16, State 1, Line 8
Invalid column name 'salary'.

为什么 SALARY 仍然是无效的列名?

【问题讨论】:

  • 你在过去几天里问了几个问题,其中大部分都必须由其他人重新格式化。请使用Code Sample 按钮获取代码,并阅读Markdown Editing Help
  • 加入 ds.averageSalary = e.Employee_ID 如何工作?你不是在这里比较工资和身份证吗?

标签: mysql sql-server-2005 tsql


【解决方案1】:

您可能启用了一些区分大小写的排序规则,这会影响列名的区分大小写。请注意,您添加的列是“薪水”,但您的查询引用了“薪水”。

纠正这种情况,你应该没问题。

请参阅this related question 了解更多信息。

(另请注意 LittleBobbyTables(伟大的昵称,顺便说一句!)对您的查询的评论 - 那里有一个奇怪的连接子句!)

【讨论】:

    【解决方案2】:

    您确定在 Employee 表中有一个薪水列吗? (例如薪水) 您添加的 Salary 列在 Department 表 (d.Salary) 上,用于存储我认为的部门的平均工资。

    正如 Paul Dixon 所说,列名的大小写也很重要。

    【讨论】:

    • 我认为此查询不需要 Department.Salary 列,您还应该使用 AVG(e.salary) 而不是 AVG(Salary) 计算平均值
    • 我同意 laurent-rpnet 并且更喜欢使用限定名称而不是使用直接列名称。 e.salary 而不是 Salary
    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 2023-02-10
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    相关资源
    最近更新 更多