“将表达式转换为数据类型int时出现算术溢出错误”左键联接临时表

jckbn6z7  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(340)

当试图左连接两个临时表时,我得到了算术溢出错误。在进行并集时,没有问题,当我将select语句更改为不使用求和函数时也没有问题。这是我的两张table:

SELECT SUM(count) count
     , EventType
     , month
FROM #engine_final
GROUP BY EventType
       , month
UNION ALL
SELECT SUM(count) count
     , EventType
     , month
FROM #circumvent_final
GROUP BY EventType
       , month

结果如下:

因此,我尝试使用以下查询对我的计数进行求和,按月份分组:

SELECT SUM(ef.count) AS EngineStarts
     , SUM(cf.count) AS Circumventions
FROM #engine_final ef
     LEFT JOIN #circumvent_final cf ON ef.month = cf.month

但这是我面对错误的时候。我想也许我已经达到了int的极限,但是我的数字只有2.6亿,所以这不可能。我错过了什么?

busg9geu

busg9geu1#

您的联接将行相乘。您应该先在子查询中预聚合,然后加入:

SELECT ef.month, ef.EngineStarts, cf.Circumventions
FROM (
    SELECT month, SUM(count) EngineStarts
    FROM #engine_final 
    GROUP BY month
) ef
LEFT JOIN (
    SELECT month, SUM(cf.count) AS Circumventions
    FROM #circumvent_final 
    GROUP BY month
) cf ON ef.month = cf.month

我不确定你是否需要 where 子查询中要在 eventType -如果需要的话,你可以很容易地添加它们。
如果你有几个月的时间 cf 那些不在 ef ,另一方面,你也可以考虑 FULL JOIN 而不是 LEFT JOIN :

SELECT 
    COALESCE(ef.month, cf.month) month, 
    COALESCE(ef.EngineStarts, 0) EngineStarts, 
    COALESCE(cf.Circumventions, 0) Circumventions
FROM (
    SELECT month, SUM(count) EngineStarts
    FROM #engine_final 
    GROUP BY month
) ef
FULL JOIN (
    SELECT month, SUM(cf.count) AS Circumventions
    FROM #circumvent_final 
    GROUP BY month
) cf ON ef.month = cf.month

相关问题