【问题标题】:Undo invalid error due to the group by clause由于 group by 子句撤消无效错误
【发布时间】:2014-07-24 09:39:49
【问题描述】:

代码出错... Staff.StaffId/Name 总是被指出为错误。 想要在supervisor ID=7和'years in service'

Column 'Staff.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.


select staffId,Name, DATEDIFF(year,DateJoin,GETDATE()) as 'Years in Service' from Staff
JOIN Branch ON Branch.BranchNo=Staff.BranchNo
where SupervisorID=7 
having COUNT(*) <10

【问题讨论】:

    标签: asp.net sql error-handling group-by


    【解决方案1】:

    最简单的解决方法是简单地将 Group By 子句添加到函数中。试试:

    select staffId,Name, DATEDIFF(year,DateJoin,GETDATE()) as 'Years in Service' from Staff
    JOIN Branch ON Branch.BranchNo=Staff.BranchNo
    where SupervisorID=7
    GROUP BY staff.name, staff.staffId
    having COUNT(*) <10
    

    【讨论】:

      【解决方案2】:

      如果您有 count() 并且想要多行,则需要 group by 子句:

      select staffId,Name, DATEDIFF(year, DateJoin, GETDATE()) as [Years in Service]
      from Staff JOIN
           Branch
           ON Branch.BranchNo = Staff.BranchNo
      where SupervisorID = 7 
      group by staffId, Name
      having COUNT(*) < 10;
      

      此外,您不应在列名中使用单引号。单引号只能用于字符串和日期常量。此外,最好使用表别名来识别每列的来源。

      【讨论】:

        【解决方案3】:

        我不确定您是否应该使用 HAVING - “AND” 可以......

        select staffId,Name, DATEDIFF(year,DateJoin,GETDATE()) as 'Years in Service' from Staff
        JOIN Branch ON Branch.BranchNo=Staff.BranchNo
        where SupervisorID=7 
        and DATEDIFF(year,DateJoin,GETDATE()) <10
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-25
          • 1970-01-01
          • 2013-05-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-31
          相关资源
          最近更新 更多