我写了一个SQL查询来获取2006年到2008年之间的员工雇用人数。这是我来自Adventurework2014.dimemployee表的代码
SELECT YEAR(cast('HireDate' as int)), DepartmentName,
count(ParentEmployeeKey) AS 'total emplyee join'
FROM DimEmployee
where HireDate between 2006 and 2008
group by DepartmentName, HireDate,FirstName,ParentEmployeeKey
ORDER BY YEAR(HireDate)
我上面的代码显示错误
操作符类型冲突:日期与smallint不兼容
请帮我一些解决方案。
答案 0 :(得分:2)
您错过了year()
子句中的where
的使用:
where year(HireDate) >= 2006 and year(HireDate) <= 2008
此外,您也无需将cast()
函数与year()
一起使用,因为它将返回数字类型。
您的SELECT
语句对我来说很奇怪,当您包含GROUP BY
时,它应该具有聚合列:
SELECT YEAR(HireDate), DepartmentName,
count(ParentEmployeeKey) AS 'total emplyee join'
FROM DimEmployee
WHERE year(HireDate) >= 2006 and year(HireDate) <= 2008
GROUP BY DepartmentName, YEAR(HireDate), FirstName, ParentEmployeeKey
ORDER BY YEAR(HireDate);
答案 1 :(得分:1)
以下语句将HireDate
作为字符串,不能转换为int。
cast('HireDate' as int)
理想情况下,您无需将其转换为int,如果您在日期上使用YEAR
,则仅会为您提供int。
按如下所示更改查询。
SELECT YEAR(HireDate), DepartmentName,
count(ParentEmployeeKey) AS 'total emplyee join'
FROM DimEmployee
where YEAR(HireDate) >= 2006 and YEAR(HireDate) <= 2008
group by DepartmentName, HireDate,FirstName,ParentEmployeeKey
ORDER BY YEAR(HireDate)
答案 2 :(得分:0)
请尝试以下操作
SELECT YEAR(cast(HireDate as date)), DepartmentName,
count(ParentEmployeeKey) AS 'total emplyee join'
FROM DimEmployee
where YEAR(cast(HireDate as date)) between 2006 and 2008
group by DepartmentName, HireDate,FirstName,ParentEmployeeKey
ORDER BY YEAR(cast(HireDate as date))
如果您的“ HireDate”列为datetime字段,则不需要任何强制转换