从varchar到bigint的转换导致聚合时出错

时间:2019-05-31 20:02:23

标签: sql sql-server casting

情况:

我想从表中汇总一个值,但是出现以下错误:

  

将数据类型varchar转换为big int时出错。

我已经在线阅读了无数种不同的解决方案,但是他们似乎并没有解决。

当前查询; 因此,根据错误消息,我只是添加了CAST函数,但仍然无法正常工作。

SELECT
    base.target_date AS target_date
  , base.game_id AS game_id                                                                                                 
  , base.device AS device
  , ISNULL(CAST(SUM(use_point.point) AS bigint),0) AS result                     
FROM 
    cte AS base

LEFT JOIN cte2 AS use_point         
    ON base.target_date = use_point.target_date 
    AND base.game_id = use_point.device
    AND base.device = use_point.device

GROUP BY
    base.target_date 
  , base.device 
  , base.game_id
WITH ROLLUP
GO

2 个答案:

答案 0 :(得分:2)

我假设use_point.pointVARCHAR,在这种情况下,只需更改您放置CAST语句的位置即可。

, ISNULL(SUM(CAST(use_point.point AS bigint)), 0) AS result                     

请注意,CAST现在发生在SUM之前。

答案 1 :(得分:2)

改为使用TRY_CAST()。它必须是SUM()的参数:

SELECT base.target_date, base.game_id, base.device,
       COALESCE(SUM(TRY_CAST(use_point.point as bigint)), 0) as result
FROM . . .

请注意,列别名是多余的,因为您正在分配默认别名。

您还应该修复数据。不要将数值存储为字符串。要查找错误数据,您可以使用:

select points
from use_points
where try_convert(points as bigint) is null and
      points is not null;
相关问题