Reputation: 181
I need to change the result of aggregate function in SQL Server 2012 to decimal
M1
and M2
are two columns in my table and their data type is int
.
I need to find sum(M1)/sum(M2)
and the result should be in 2 decimal places.
How can I achieve this?
Upvotes: 1
Views: 453
Reputation: 3866
You need to convert the values before division. Please, read BOL article Data Type Precedence
CAST(SUM(M1) as DECIMAL(10,2))/CAST(SUM(M2) as DECIMAL(10,2)
Upvotes: 0
Reputation: 5307
I believe you need to cast both to decimals. The result will then be a decimal without other inferred type conversions
cast(sum(M1) as decimal(9,2))/cast(sum(M2) as decimal(9,2))
Precision, Scale, and Length (Transact-SQL)
Upvotes: 3