简体   繁体   English

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

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

i have write a sql query to fetch employee hire count between 2006 to 2008 . 我已经写了一个SQL查询来获取2006年到2008年之间的员工雇佣数。 here is my code from adventurework2014.dimemployee table 这是来自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)

my above code showing error 我上面的代码显示错误

Operand type clash: date is incompatible with smallint 操作数类型冲突:日期与smallint不兼容

please help me with some solution . 请帮我解决一下。

You missed to use year() in where clause : 你错过了在where子句中使用year()

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

Further more you also don't need to use cast() function with year() as it will return numeric type. 此外,您还不需要对year()使用cast()函数,因为它将返回数字类型。

Your SELECT statement is strange for me it should have aggregated column when you include GROUP BY : 你的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);

Below statement will take HireDate as string, which can't be converted to int. 下面的语句将HireDate作为字符串,不能转换为int。

cast('HireDate' as int)

Ideally you don't need to convert it into int, if you use YEAR on date, it will give you int only. 理想情况下,您不需要将其转换为int,如果您在日期使用YEAR ,它将仅为您提供int。

Change your query like following. 更改您的查询,如下所示。

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)

Please try the below, 请尝试下面的,

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))

If your column 'HireDate' is datetime field , you don't need any cast 如果您的列“HireDate”是日期时间字段,则不需要任何强制转换

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

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