SQL: left join and sum: 将表达式转换为数据类型 int 的算术溢出错误

SQL: left join and sum: Arithmetic overflow error converting expression to data type int

我有这个查询:

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 用于外连接 table.

的求和

我能做什么?

如果您在一家金融公司工作,

sum(r.Amount) as Pays

很可能会溢出 20 亿的微不足道的整数限制。您可以转换为更大的变量类型,like a decimal:

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

试试这个

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