【问题标题】:Operand type clash: date is incompatible with smallint error in sql server操作数类型冲突:日期与 sql server 中的 smallint 错误不兼容
【发布时间】:2019-01-23 11:07:41
【问题描述】:

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

请帮我解决一下。

【问题讨论】:

    标签: sql sql-server-2017


    【解决方案1】:

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

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

    【讨论】:

    • 我认为它也应该避免转换为hiredate的int
    【解决方案2】:

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

    【讨论】:

    • 现在完美。我学到了关于年份功能和演员表功能的非常重要的东西。谢谢
    【解决方案3】:

    请尝试以下,

    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' 是日期时间字段,则不需要任何演员表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      相关资源
      最近更新 更多