簡體   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