user3458120
user3458120

Reputation: 181

Change the result to decimal in sql server

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

Answers (2)

Igor Borisenko
Igor Borisenko

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

sarin
sarin

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

Related Questions