drcoding
drcoding

Reputation: 173

SQL cast an Int value or multiply by 1.0, best option

I had a quick question that related to dividing one Integer by another Integer.

I would like to know peoples thoughts on either casting one of the Integer values as a Float, or multiplying it by 1.0, which seems to have the same effect.

cast(sum(case when [Column1] = 'Value' then 1 else 0 end) As Float) / [Column2]

OR

1.0 * sum(case when [Column1] = 'Value' then 1 else 0 end) / [Column2]

Other than obviously being able to choose your data type when casting, in the calculation, should they should always return the same result?

Upvotes: 4

Views: 3196

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269773

I would argue that putting in floating point constants is the best approach:

sum(case when [Column1] = 'Value' then 1.0 else 0 end) / [Column2]

If you are going to do a conversion, do so after the division, so you control the type of the result.

Upvotes: 1

Related Questions