SQL:左连接和求和:将表达式转换为数据类型int的算术溢出错误

时间:2015-06-07 20:39:51

标签: sql-server aggregate-functions outer-join

我有这个问题:

select p.UserName, sum(b.PercentRials) as amount, sum(r.Amount) as Pays
from bills b inner join UserProfiles p on b.PayerUserName=p.UserName
left outer join PayReceipts r on p.UserName=r.UserName
where p.[Percent]>0 and b.PayDate>'2014-11-20'
group by p.UserName

运行时出现此错误:

Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type int.
Warning: Null value is eliminated by an aggregate or other SET operation.

我可以理解外连接会导致此错误,因为当我删除最后一个总和时,它运行正常。但是我记得做过这样的查询并在外连接表上获得NULL求和。

我该怎么办?

2 个答案:

答案 0 :(得分:3)

试试这个

select p.UserName, sum(b.PercentRials) as amount, sum(CAST (r.Amount AS BIGINT)) as Pays
from bills b inner join UserProfiles p on b.PayerUserName=p.UserName
left outer join PayReceipts r on p.UserName=r.UserName
where p.[Percent]>0 and b.PayDate>'2014-11-20'
group by p.UserName

SUM中的表达式类型决定了输出的类型。因此,当您的总和超过整数限制时,您将收到此错误。要在不收到错误的情况下将您的数据视为整数,您需要cast amount列为BIGINT,因此总和将为BIGINT类型。

答案 1 :(得分:2)

如果您在金融公司工作,

sum(r.Amount) as Pays

可能会很好地溢出20亿的微小整数限制。您可以转换为更大的变量类型like a decimal

sum(cast(r.Amount as decimal(38,2))) as Pays