繁体   English   中英

由于group by子句,撤消无效错误

[英]Undo invalid error due to the group by clause

代码出错... Staff.StaffId / Name总是被指出为错误。 想要选择职员ID,anem和服务年限,条件是主管ID = 7并且“服务年限” <10

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

最简单的解决方法是将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

如果您有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;

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

我不确定您是否应该使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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