繁体   English   中英

操作数类型冲突:日期与sql server中的smallint错误不兼容

[英]Operand type clash: date is incompatible with smallint error in sql server

我已经写了一个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不兼容

请帮我解决一下。

你错过了在where子句中使用year()

where year(HireDate) >= 2006 and year(HireDate) <= 2008 

此外,您还不需要对year()使用cast()函数,因为它将返回数字类型。

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

下面的语句将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)

请尝试下面的,

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”是日期时间字段,则不需要任何强制转换

暂无
暂无

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

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