简体   繁体   中英

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 . here is my code from adventurework2014.dimemployee table

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

please help me with some solution .

You missed to use year() in where clause :

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.

Your SELECT statement is strange for me it should have aggregated column when you include 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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